Adapter模式:把一个接口转换为另一个接口。
Decorator模式:给一个对象动态增加功能。比如Java的 new BufferedOutputStream(new FileOutputStream(new File("a-file-name"))),BufferedOutputStream就给FileOutputStream对象增加了缓冲写的功能。此即Decorator模式。
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++直接。
- // tst.cpp : Defines the entry point for the console application.
- //
- /*
- result:
- 1314091501
- 1
- 1314091501
- 2
- */
- #include "stdafx.h"
- #include <iostream>
- #include <string>
- #include <time.h>
- using namespace std;
- class Basic {
- public:
- long val;
- };
- template <class T>
- class TimeStamp: public T
- {
- private:
- long timestamp;
- public:
- TimeStamp() {
- timestamp=time(NULL);
- }
- long getTimeStamp() {
- return timestamp;
- }
- };
- template <class T>
- class SerialNumbered: public T
- {
- private:
- long serialNumber;
- static long counter;
- public:
- SerialNumbered() {
- serialNumber = ++ counter;
- }
- long getSerialNumber() {
- return serialNumber;
- }
- };
- template <class T>
- long SerialNumbered<T>::counter = 0;
- int main(int argc, char* argv[])
- {
- SerialNumbered< TimeStamp<Basic> > b1;
- int i;
- for(i=0;i<100000000;i++);
- SerialNumbered< TimeStamp<Basic> > b2;
- printf("%u\n",b1.getTimeStamp());
- printf("%u\n",b1.getSerialNumber());
- printf("%u\n",b2.getTimeStamp());
- printf("%u\n",b2.getSerialNumber());
- return 0;
- }
Proxy模式:一个对象作为另一个对象的代理,或占位,可以控制对被代理的访问。RPC经常采用Proxy模式,用户通过本地对象,访问远程对象。
Reference
Thinking in Java
Design Patterns