適配器模式分爲兩種:類適配器模式和對象適配器模式。廢話很少說,直接上代碼。this
一、類適配器模式spa
public interface TargetInterface { void method1(); void method2(); } /** * 須要被適配的類,該類要實現TargetInterface接口,可是不能被修改。 * */ class Adaptee { public void method1() { System.out.println("method1"); } } /** * 適配器類 * */ class Adapter extends Adaptee implements TargetInterface { public void method2() { System.out.println("method2"); } } public class AdapterTest { public static void main(String[] args) { Adapter adapt = new Adapter(); adapt.method1(); adapt.method2(); } }
二、對象適配器模式code
public interface TargetInterface { void method1(); void method2(); } /** * 須要被適配的類,該類要實現TargetInterface接口,可是不能被修改。 * */ class Adaptee{ public void method1(){ System.out.println("method1"); } } /** * 適配器類 * */ class Adapter implements TargetInterface { private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } public void method1() { this.adaptee.method1(); } public void method2() { System.out.println("method2"); } } public class AdapterTest { public static void main(String[] args) { Adapter adapt = new Adapter(new Adaptee()); adapt.method1(); adapt.method2(); } }