适配器模式
1.转换接头
2.代码:
C++
1 //adapter c++ 2 #include<iostream> 3 using namespace std; 4 5 class Target{ 6 public: 7 virtual void request(){ 8 cout<<"Target request called"<<endl; 9 } 10 }; 11 12 class Adaptee{ 13 public: 14 void specificRequest(){ 15 cout<<"Adaptee specificRequest called"<<endl; 16 } 17 }; 18 19 class Adaptor : public Target{ 20 public: 21 Adaptor(Adaptee *p):p_adp(p){} 22 void request(){ 23 p_adp->specificRequest(); 24 } 25 private: 26 Adaptee *p_adp; 27 }; 28 29 int main(){ 30 Adaptee* p_adp = new Adaptee(); 31 Target * p_client = new Adaptor(p_adp); 32 p_client->request(); 33 34 return 0; 35 }
Java:
1 //adapter java 2 import java.util.*; 3 4 class EnumerationIterator implements Iterator<Object>{ 5 Enumeration<?> m_enum; 6 public EnumerationIterator(Enumeration<?> t_enum){ 7 this.m_enum = t_enum; 8 } 9 public boolean hasNext(){ 10 return m_enum.hasMoreElements(); 11 } 12 public Object next(){ 13 return m_enum.nextElement(); 14 } 15 public void remove(){ 16 throw new UnsupportedOperationException(); 17 } 18 } 19 20 class IteratorEnumeration implements Enumeration<Object>{ 21 Iterator<?> iterator; 22 public IteratorEnumeration(Iterator<?> iterator){ 23 this.iterator = iterator; 24 } 25 public boolean hasMoreElements(){ 26 return iterator.hasNext(); 27 } 28 public Object nextElement(){ 29 return iterator.next(); 30 } 31 } 32 33 public class EnumerationIteratorTest{ 34 public static void main(String[] args){ 35 // 36 Vector<String> v = new Vector<String>(Arrays.asList(args)); 37 Iterator<?> iterator = new EnumerationIterator(v.elements()); 38 while(iterator.hasNext()){ 39 System.out.println(iterator.next()); 40 } 41 System.out.print("\n"); 42 // 43 Enumeration<?> enumeraton = new IteratorEnumeration(v.iterator()); 44 while(enumeraton.hasMoreElements()){ 45 System.out.println(enumeraton.nextElement()); 46 } 47 } 48 }
3.杂记:
1.<?>表示具有某种特定类型的非原生的Object
2. 装饰者 :不改变接口,加入责任
适配器 :将一个接口转换成另一个
外观模式 :让接口简单
从意图的角度区分(适配器和外观)而不是看封装了几个类
3.对象适配器 和 类适配器:Java不支持多继承,类适配器不可
4.最少知识原则(= law of demeter),免得修改一部分影响到其他;A.B() ; not A.C().B()
抽象与速度间取舍,适度