您的位置:首页 > 编程语言 > C语言/C++

C语言设计模式:工厂和抽象工厂

2013-02-11 18:09 344 查看
/article/1797633.html

/article/1797631.html

这哥们两个例子举得非常好。

工厂就是提取产品的一个维度,抽象工厂就是多个维度,甚至于把工厂也抽象了。

如果说工厂模式搞多个参数支持多个维度,也行,但代码就难看了。

从代码可以看出来,这两种模式的缺陷就是,需要事先知道产品的类型。

[cpp] view
plaincopy

typedef struct _Shoe

{

int type;

void (*print_shoe)(struct _Shoe*);

}Shoe;

就像上面说的,现在有胶鞋,那也有皮鞋,我们该怎么做呢?

[cpp] view
plaincopy

void print_leather_shoe(struct _Shoe* pShoe)

{

assert(NULL != pShoe);

printf("This is a leather show!\n");

}

void print_rubber_shoe(struct _Shoe* pShoe)

{

assert(NULL != pShoe);

printf("This is a rubber shoe!\n");

}

所以,对于一个工厂来说,创建什么样的鞋子,就看我们输入的参数是什么?至于结果,那都是一样的。

[cpp] view
plaincopy

#define LEATHER_TYPE 0x01

#define RUBBER_TYPE 0x02

Shoe* manufacture_new_shoe(int type)

{

assert(LEATHER_TYPE == type || RUBBER_TYPE == type);

Shoe* pShoe = (Shoe*)malloc(sizeof(Shoe));

assert(NULL != pShoe);

memset(pShoe, 0, sizeof(Shoe));

if(LEATHER_TYPE == type)

{

pShoe->type == LEATHER_TYPE;

pShoe->print_shoe = print_leather_shoe;

}

else

{

pShoe->type == RUBBER_TYPE;

pShoe->print_shoe = print_rubber_shoe;

}

return pShoe;

[cpp] view
plaincopy

typedef struct _Apple

{

void (*print_apple)();

}Apple;

typedef struct _Grape

{

void (*print_grape)();

}Grape;

上面分别对苹果和葡萄进行了抽象,当然它们的具体函数也是不一样的。

[cpp] view
plaincopy

void print_white_apple()

{

printf("white apple!\n");

}

void print_red_apple()

{

printf("red apple!\n");

}

void print_white_grape()

{

printf("white grape!\n");

}

void print_red_grape()

{

printf("red grape!\n");

}

完成了水果函数的定义。下面就该定义工厂了,和水果一样,我们也需要对工厂进行抽象处理。

[cpp] view
plaincopy

typedef struct _FruitShop

{

Apple* (*sell_apple)();

Apple* (*sell_grape)();

}FruitShop;

所以,对于卖白苹果、白葡萄的水果店就该这样设计了,红苹果、红葡萄的水果店亦是如此。

[cpp] view
plaincopy

Apple* sell_white_apple()

{

Apple* pApple = (Apple*) malloc(sizeof(Apple));

assert(NULL != pApple);

pApple->print_apple = print_white_apple;

return pApple;

}

Grape* sell_white_grape()

{

Grape* pGrape = (Grape*) malloc(sizeof(Grape));

assert(NULL != pGrape);

pGrape->print_grape = print_white_grape;

return pGrape;

}

这样,基本的框架就算搭建完成的,以后创建工厂的时候,

[cpp] view
plaincopy

FruitShop* create_fruit_shop(int color)

{

FruitShop* pFruitShop = (FruitShop*) malloc(sizeof(FruitShop));

assert(NULL != pFruitShop);

if(WHITE == color)

{

pFruitShop->sell_apple = sell_white_apple;

pFruitShop->sell_grape = sell_white_grape;

}

else

{

pFruitShop->sell_apple = sell_red_apple;

pFruitShop->sell_grape = sell_red_grape;

}

return pFruitShop;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐