C语言设计模式:外观模式

A facade is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:

  • make a software library easier to use, understand and test, since the facade has convenient methods for common tasks;
  • make the library more readable, for the same reason;
  • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system;
  • wrap a poorly designed collection of APIs with a single well-designed API (as per task needs).

外观模式是C中最常见的“模式”。简单的说,就是一系列过程的打包。和CPP的差异是,CPP中设计到对不同对象的方法的封装,C中一般没有对象,只有过程。

外观模式是比较简单的模式。它的目的也是为了简单。什么意思呢?举个例子吧。以前,我们逛街的时候吃要到小吃一条街,购物要到购物一条街,看书、看电影要到文化一条街。那么有没有这样的地方,既可以吃喝玩乐,同时相互又靠得比较近呢。其实,这就是悠闲广场,遍布全国的万达广场就是干了这么一件事。

    首先,我们原来是怎么做的。

[cpp]  view plain copy
  1. typedef struct _FoodSteet  
  2. {  
  3.     void (*eat)();  
  4. }FoodStreet;      
  5.   
  6. void eat()  
  7. {  
  8.     printf("eat here!\n");  
  9. }  
  10.   
  11. typedef struct _ShopStreet  
  12. {  
  13.     void (*buy)();  
  14. }ShopStreet;  
  15.   
  16. void buy()  
  17. {  
  18.     printf("buy here!\n");  
  19. }  
  20.   
  21. typedef struct _BookStreet  
  22. {  
  23.     void (*read)();  
  24. }BookStreet;  
  25.   
  26. void read()  
  27. {  
  28.     printf("read here");  
  29. }  
    下面,我们就要在一个plaza里面完成所有的项目,怎么办呢?

[cpp]  view plain copy
  1. typedef struct _Plaza  
  2. {  
  3.     FoodStreet* pFoodStreet;  
  4.     ShopStreet* pShopStreet;  
  5.     BookStreet* pBookStreet;  
  6.   
  7.     void (*play)(struct _Plaza* pPlaza);   
  8. }Plaza;  
  9.   
  10. void play(struct _Plaza* pPlaza)  
  11. {  
  12.     assert(NULL != pPlaza);  
  13.   
  14.     pPlaza->pFoodStreet->eat();  
  15.     pPlaza->pShopStreet->buy();  
  16.     pPlaza->pBookStreet->read();  
  17. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值