AdapterPattern(适配器模式)

时间:2022-04-25 07:32:54
import org.omg.PortableServer.AdapterActivator;

/**
* 分两种情况:
* 1.类适配器
* 2.对象适配器
* 作用:让原本接口不兼容的两个类可以在一起工作
* 比如说三孔插座适配两孔的,适配器只能配的更少,比如三孔配成两孔
* @author TMAC-J
*
*/
1.类适配器
public class AdapterPattern { public class Adaptee{
public void doSomething(){
System.out.println("doSomething...");
}
} interface Target{
void doOtherSomething();
} public class Adapter extends Adaptee implements Target{
@Override
public void doOtherSomething() {
super.doSomething();
}
} public void test(){
Target target = new Adapter();
target.doOtherSomething();
} } 2.对象适配器       

public class Adaptee{
public void doSomething(){
System.out.println("doSomething...");
}
}

interface Target{
void doOtherSomething();
}

public class Adapter extends Adaptee implements Target{

private Adaptee adaptee;

public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}

@Override
public void doOtherSomething() {
adaptee.doSomething();
}
}

public void test(){
Target target = new Adapter(new Adaptee());
target.doOtherSomething();
}