2014年写过一篇实现,重读一遍《设计模式》,参考网上的一篇文章,又重新写了一遍。
我体会到,c++的类在c语言里面用struct代替之后,c++的this指针可以通过传入struct本身的指针来完成。
而在command模式里的Command实际上既包含了对象(pData),又包含了命令接口(exe)。
#include <stdio.h>
#include <stdlib.h>
#include <cassert>
#define COMMAND_SLOT_MAX (2)
typedef struct _Command
{
void* pData;
void (*exe)(struct _Command* pCommand);
}Command;
typedef struct _RemoteControl
{
Command onCommands[COMMAND_SLOT_MAX];
Command offCommands[COMMAND_SLOT_MAX];
void (*setCommand)(int slot, Command onCommand, Command offCommand, struct _RemoteControl *pRemoteControl);
void (*onButtonWasPushed)(int slot, struct _RemoteControl *pRemoteControl);
void (*offButtonWasPushed)(int slot, struct _RemoteControl *pRemoteControl);
}RemoteControl;
void setCommand(int slot, Command onCommand, Command offCommand, struct _RemoteControl *pR