C语言中一个结构体代表一个类,用此结构体命名一个变量称为该类的一个详细对象
C语言的简单工厂模式:此处自己的理解为将各个模块功能封装起来用链表的方式将各个模块进行连接,这样程序的可拓展性和纠错性大大提高。
#include"contralDevices.h"
#include"InputCommand.h"
struct devices *findDeviceByname(char *name ,struct devices *phead)
{
struct devices *tmp = phead;
if(phead == NULL){
printf("ok0\n");
return NULL;
}
else{
while(tmp != NULL){
if(strcmp(tmp->deviceName,name) == 0){
return tmp;
}
tmp = tmp->nextdv;
}
return NULL;
}
}
int main()
{
char name[128] = {'\0'};
struct devices *tmp;
struct devices *pdeviceHead = NULL;
struct InputCommander *pCommanderHead = NULL;
if(wiringPiSetup() == -1){
printf("failed\n");
return -1;
}
pdeviceHead = addBathroomLightTodeviceLink(pdeviceHead);
pdeviceHead = addLivingroomLightTodeviceLink(pdeviceHead);//构建链表
printf("please input cmd\n");
scanf("%s",&name);
tmp = findDeviceByname(name,pdeviceHead);
printf("ok\n");
if(tmp != NULL){
printf("ok1\n");
tmp->deviceInit(tmp->pinNum);
// tmp->open(tmp->pinNum);
}
return 0;
}
功能模块//头文件
#include<wiringPi.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
struct devices
{
char deviceName[128];
int status;
int pinNum;
int (*open)(int pinNum);
int (*close)(int pinNum);
int (*deviceInit)(int pinNum);
int (*readStatus)();
int (*changeStatus)(int status);
struct devices *nextdv;
};
struct devices *addBathroomLightTodeviceLink(struct devices *phead);
struct devices *addUpstairLightTodeviceLink(struct devices *phead);
功能一
#include"contralDevices.h"
int bathroomLightOpen(int pinNum)
{
digitalWrite(pinNum,LOW);
printf("ok3\n");
}
int bathroomLightClose(int pinNum)
{
digitalWrite(pinNum,HIGH);
}
int bathroomLightCloseInit(int pinNum)
{
pinMode(pinNum,OUTPUT);
digitalWrite(pinNum,HIGH);
}
struct devices bathroomLight = {
.deviceName = "bathroomLight",
.pinNum = 22,
.open = bathroomLightOpen,
.close = bathroomLightClose,
.deviceInit = bathroomLightCloseInit,
.changeStatus = bathroomLightCloseStatus
};
struct devices *addBathroomLightTodeviceLink(struct devices *phead)
{
if(phead == NULL){
printf("ok2\n");
return &bathroomLight;
}else{
bathroomLight.nextdv = phead;
phead = &bathroomLight;
printf("ok3\n");
return phead;
}
}
功能二
#include"contralDevices.h"
int livingroomLightOpen(int pinNum)//开卧室灯
{
digitalWrite(pinNum,LOW);
printf("ok3\n");
}
int livingroomLightClose(int pinNum)//关卧室灯
{
digitalWrite(pinNum,HIGH);
}
int livingroomLightCloseInit(int pinNum)//初始化
{
pinMode(pinNum,OUTPUT);
digitalWrite(pinNum,HIGH);
}
struct devices livingroomLight = {//初始化卧室灯结构体
.deviceName = "livingroomLight",
.pinNum = 23,
.open = livingroomLightOpen,
.close = livingroomLightClose,
.deviceInit = livingroomLightCloseInit,
.changeStatus = livingroomLightCloseStatus
};
struct devices *addLivingroomLightTodeviceLink(struct devices *phead)//把卧室灯加到设备链表中
{
if(phead == NULL){
printf("ok2\n");
return &livingroomLight;
}else{
livingroomLight.nextdv = phead;
phead = &livingroomLight;
printf("ok3\n");
return phead;
}
}
师上官可编程