有没有一种简单的方法来编码ANSI C中的策略(或其他)设计模式,这将适合11“ MacBook Air? [英] Is there a simple way to code the strategy (or other) design pattern in ANSI C that would fit on the screen of an 11" MacBook Air?
问题描述
似乎ANSI C中的OO不是今天对OO的青睐的方法。有没有人知道使用严格的ANSI C来编写一个简单的设计模式的方式,所以我可以向朋友证明这是可能的(Axel-Tobias Schreiners的书让我进行这个!)
It seems that OO in ANSI C is not the favored approach to OO today. Does anyone know of a way to code a simple design pattern using strict ANSI C so I can prove to a friend that it is possible?(Axel-Tobias Schreiners' book got me going on this!)
推荐答案
使用C的OO可以使用函数指针来实现,如在这个SO问题。
OO using C can indeed be implemented using function pointers as explained quite well in this SO question.
使用该帖子的信息,以下是我将如何使用基本继承在C中实现Strategy模式。
Using the info from that post, here's how I would implement a Strategy pattern in C using basic inheritance.
让我们使用以下C ++作为指导:
Lets use the following C++ as a guide:
class StrategyBase
{
...
StrategyBase();
virtual void strategyMethod() = 0;
...
};
class StrategyDerived
{
...
StrategyDerived();
void strategyMethod();
...
};
这里是相应的C代码:
typedef struct StrategyBase_t StrategyBase;
struct StrategyBase_t
{
StrategyBase *base; /* must be first memeber */
void (*strategyMethod)(const void *self);
};
StrategyBase *newStrategyBase();
void strategyMethod(const void *self); /* the abstract method */
struct StrategyDerived
{
StrategyBase *base; /* must be first memeber */
void (*strategyMethod)(const void *self);
/* more derived attributes here */
};
typedef struct StrategyDerived_t StrategyDerived;
StrategyDerived *newStrategyDerived();
这里是功能实现:
void strategyMethod(const void *self)
{
/* If called with just a StrategyBase, strategyMethod will be NULL, *
* so perhaps some sort of protection should be added here first */
((StrategyBase*) self)->base->strategyMethod();
}
void strategyMethodDerived(const void *self)
{
/* Put your implementation here */
}
/* StrategyBase constructor */
StrategyBase *newStrategyBase()
{
StrategyBase *self = (StrategyBase*) malloc(sizeof(StrategyBase));
self->base = self; /* See comment below about virtual table */
self->strategyMethod = NULL; /* StrategyBase is abstract, right? */
return self;
}
/* StrategyDerived constructor */
StrategyDerived *newStrategyDerived()
{
StrategyDerived *self = (StrategyDerived*) malloc(sizeof(StrategyDerived));
self->base = newStrategyBase();
self->strategyMethod = self->base->strategyMethod = strategyMethodDerived;
return self;
}
虚拟表实现非常基本,但应该工作理想情况下,应该实现更加健壮的东西。
The virtual table implementation is very basic, but should work. Ideally, something more robust should be implemented.
然后,您只需要在需要一个策略的Struct中使用一个指向StrategyBase的指针,并且您已经实现了一个策略模式在C.我没有尝试编译它,但这应该是一个好的起点。
Then you just have to use a pointer to StrategyBase in a Struct that needs a strategy, and there you have a strategy pattern implemented in C. I havent tried compiling it, but this should serve as a good starting point.
这篇关于有没有一种简单的方法来编码ANSI C中的策略(或其他)设计模式,这将适合11“ MacBook Air?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!