Adapter (适配器模式)
适配器模式:
将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
有两种适配器模式:
1)类适配器 (通过继承的方式)
2)对象适配器 (采取对象组合的模式)
-------------------------- 类适配器 -----------------------------
Target.java
- package com.adapter ;
- public interface Target
- {
- public void method() ;
- }
被适配器类
Adaptee.java
- package com.adapter ;
- public class Adaptee
- {
- public void method2()
- {
- System.out.println("Adapter-->method2()") ;
- }
- }
适配器类 Adapter.java
- package com.adapter ;
- public class Adapter extends Adaptee implements Target
- {
- public void method()
- {
- super.method2() ;//或者this.method2() ;
- }
- }
Client.java
- package com.adapter ;
- public class Client
- {
- public static void main(String[] args)
- {
- Target t = new Adapter() ;
- t.method() ;
- }
- }
-------------------------- 对象适配器 -----------------------------
Target.java
- package com.adapter ;
- public interface Target
- {
- public void method() ;
- }
被适配器类
Adaptee.java
- package com.adapter ;
- public class Adaptee
- {
- public void method2()
- {
- System.out.println("Adapter-->method2()") ;
- }
- }
适配器类 Adapter.java
- package com.adapter ;
- public class Adapter implements Target
- {
- private Adaptee adaptee;
- public Adapter(Adaptee adaptee)
- {
- this.adaptee = adaptee ;
- }
- public void method()
- {
- this.adaptee.method2() ;
- }
- }
Client.java
- package com.adapter ;
- public class Client
- {
- public static void main(String[] args)
- {
- Adaptee adaptee = new Adaptee() ;
- Target t = new Adapter(adaptee) ;
- t.method() ;
- }
- }
你们都是有经验的开发人员