command模式(c语言实现)

本文是作者重读《设计模式》后,根据网上资源再次实现的C语言版本命令模式。在C语言中,作者利用struct替代了C++的类,并通过传入struct指针模拟this指针。Command在该模式中包含对象和命令接口。
摘要由CSDN通过智能技术生成

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值