天天看点

适配器模式

目的:原接口的参数等不满足现有条件,或者完全不同,同时不想改变原接口。

优点:1.可以让任何两个没有关联的类一起运行

           2。提高了类的复用,解决了现存类和复用环境要求不一致的问题

缺点:增加了类的数量,增加了结构的复杂性。

类适配器:

适配器需要实现接口

类图:

适配器模式

代码:

新增的接口(想调用老接口)

1. interface Target
2. {
3. public void newMethod();
4. }      

原有的接口

1. public interface OldMethod{
2. 
3. void oldMethod();
4. }      

原有的接口实现

1. public class OldMethodImpl implements  OldMethod{
2. 
3.     @Override
4. public void oldMethodImpl() 
5.            {老方法,被调用");
6.     }
7. 
8. }      

适配器

1. public class Adapter extends OldMethodImpl implements NewMethod{
2. 
3. @Override
4.     public void newMethod() {
5.         oldMethodImpl();
6.     }
7. 
8. }      

调用

1. 
2. public class App {
3. 
4. public static void main(String[] args) {
5. 
6. Target target= new Adapter();
7.         target.newMethod();
8.     }
9. }      

采用组合方式

适配器模式

适配器类

1. class ObjectAdapter implements Target
2. {
3. private OldMethodImpl oldMethodImpl ;
4. public ObjectAdapter(OldMethodImpl oldMethodImpl)
5.     {
6. this.oldMethodImpl=oldMethodImpl;
7.     }
8. public void newMethod()
9.     {
10.         oldMethodImpl.oldMethodImpl();
11.     }
12. }      
1. public class ObjectAdapterTest
2. {
3. public static void main(String[] args)
4.     {
5. OldMethodImpl oldMethodImpl = new OldMethodImpl();
6. Target target = new ObjectAdapter(adaptee);
7.         target.newMethod();
8.     }
9. }      

继续阅读