设计模式--Mixin模式

 

设计模式--Mixin模式

分类: design&architecture   322人阅读  评论(0)  收藏  举报
Adapter模式:把一个接口转换为另一个接口。

Decorator模式:给一个对象动态增加功能。比如Java的 new BufferedOutputStream(new FileOutputStream(new File("a-file-name"))),BufferedOutputStream就给FileOutputStream对象增加了缓冲写的功能。此即Decorator模式。


Mixin模式: 笼统地说就是综合多个类的功能产生一个类,但不用多继承。下面是一个C++的Mixin模式的实现。Java用Decorator可以实现Mixin,Java也可以通过动态代理(Dynamic Proxy)来实现Mixin,但看起来都不如C++直接。

[cpp]  view plain copy
  1. // tst.cpp : Defines the entry point for the console application.  
  2. //  
  3. /* 
  4. result: 
  5. 1314091501 
  6. 1 
  7. 1314091501 
  8. 2 
  9.  
  10.  
  11. */  
  12.   
  13. #include "stdafx.h"  
  14. #include <iostream>  
  15. #include <string>  
  16. #include <time.h>  
  17. using namespace std;   
  18.   
  19. class Basic {  
  20. public:  
  21.     long val;   
  22. };  
  23.   
  24. template <class T>  
  25. class TimeStamp: public T  
  26. {  
  27.     private:  
  28.         long timestamp;  
  29.     public:  
  30.         TimeStamp() {  
  31.             timestamp=time(NULL);  
  32.         }  
  33.         long getTimeStamp() {  
  34.             return timestamp;   
  35.         }  
  36. };   
  37.   
  38. template <class T>  
  39. class SerialNumbered: public T  
  40. {  
  41.     private:  
  42.         long serialNumber;  
  43.         static long counter;   
  44.     public:  
  45.         SerialNumbered() {  
  46.             serialNumber = ++ counter;   
  47.         }  
  48.         long getSerialNumber() {  
  49.             return serialNumber;   
  50.         }  
  51. };  
  52.   
  53. template <class T>  
  54. long  SerialNumbered<T>::counter = 0;  
  55.   
  56.   
  57.   
  58. int main(int argc, char* argv[])  
  59. {  
  60.       
  61.     SerialNumbered< TimeStamp<Basic> > b1;  
  62.     int i;  
  63.     for(i=0;i<100000000;i++);  
  64.     SerialNumbered< TimeStamp<Basic> > b2;  
  65.     printf("%u\n",b1.getTimeStamp());  
  66.     printf("%u\n",b1.getSerialNumber());  
  67.     printf("%u\n",b2.getTimeStamp());  
  68.     printf("%u\n",b2.getSerialNumber());  
  69.     return 0;  
  70. }  


Proxy模式:一个对象作为另一个对象的代理,或占位,可以控制对被代理的访问。RPC经常采用Proxy模式,用户通过本地对象,访问远程对象。

Reference

Thinking in Java

Design Patterns

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值