适配器模式:将一个类的接口转换为客户需要的目标接口
一、类适配器模式
这个用变压器的列子再好不过了,大话设计模式--(朋友从美国带回个微波炉,美国电压110V,中国电压220V,幸好朋友有先见知名,带了个变压器);
现在我们来模拟一下:
/** 原角色、当前可使用220v*/
public class Adaptee {
public void provide220V(){
System.out.println("220V 电压开始工作");
}
}
/** 目标角色 */
public interface Target {
public void provide220V();
public void provide110V();
}
/**适配器角色*/
public Adapter extends Adatee implements Target{
@Override
public void provide110V() {
System.out.println("110V 电压开始工作");
}
}
/** 客户端用列*/
public class Client {
public static void main(String[] args) {
Target adapter = new Adapter();/*适配器*/
adapter.provide110V();
adapter.provide220V();
}
}
二、对象适配器模式(有一个插座,这个插座是三个口的,但是我们手上只有两个触角的插头,方法就是找一个转换头来)
/**原角色*/
/**
* 二孔插板
*/
public interface TwoSpile {
void workTwo();
}
public class Adaptee implements TwoSpile {
@Override
public void workTwo() {
// TODO Auto-generated method stub
System.out.println("二孔插座工作。。。");
}
}
/**目标角色**/
/**
* 三孔插板
*/
public interface Target {
public void workThree();
public void workTwo();
}
/**适配器*/
public class Adapter implements Target {
private TwoSpile twoSpile;
public Adapter(TwoSpile twoSpile) {
this.twoSpile = twoSpile;
}
public TwoSpile getTwoSpile() {
return twoSpile;
}
public void setTwoSpile(TwoSpile twoSpile) {
this.twoSpile = twoSpile;
}
@Override
public void workThree() {
// TODO Auto-generated method stub
System.out.println("三孔插座工作....");
}
@Override
public void workTwo() {
this.twoSpile.workTwo();
}
/**测试用例*/
public class Client {
public static void main(String[] args) {
TwoSpile twoSpile = new Adaptee();
Target threeSpile = new Adapter(twoSpile);
threeSpile.workThree();
threeSpile.workTwo();
}
}