类模式
我们知道插座的电压为交流电220V,而日常电器使用的是直流电且电压会较小,比如手机充电会通过插头适配器达到额定的输入电流。下面我们实现这个案例:将220V电压转化为5V的电压。


package Adapter.Class;
public class Adapter extends Power220V implements Power5V {
@Override
public int output5V() {
int input = output220V();
int output = input/44;
return output;
}
}
package Adapter.Class;
public class Client {
public static void main(String[] args) {
Phone phone = new HuaWei();
phone.charging(new Adapter());
}
}
package Adapter.Class;
public class HuaWei implements Phone{
@Override
public void charging(Adapter adapter) {
System.out.println("华为手机适配电压5伏");
if(adapter.output5V()==5) System.out.println("华为手机充电成功");
else System.out.println("华为手机充电不成功");
}
}
package Adapter.Class;
public interface Phone {
public void charging(Adapter adapter);
}
package Adapter.Class;
public interface Power5V {
public int output5V();
}
package Adapter.Class;
public class Power220V {
private int power = 220;
public int output220V() {
System.out.println("电压" + power + "伏");
return power;
}
}

这种模式被称作类模式,可以看到Adapter继承了Adaptee(要适配者)并且实现了Target(要适配者)。对于一对一的适配还有一种模式叫对象模式,在这种模式下,Adaptee会作为Adapter的成员属性而不是让Adapter去继承Adaptee。
对象模式


package Adapter.Object;
public class Adapter implements Power5V {
Power220V power220V;
public Adapter() {
}
public Adapter(Power220V power220V) {
this.power220V = power220V;
}
@Override
public int output5V() {
int input = power220V.output220V();
int output = input/44;
return output;
}
}
package Adapter.Object;
public class Client {
public static void main(String[] args) {
Phone phone = new HuaWei();
phone.charging(new Adapter(new Power220V()));
}
}

双向模式
上面的案例介绍了一对一的适配,还有一种适配是双向的。下面用一个案例介绍:实现猫学狗叫和狗学猫抓老鼠。


package Adapter.BothWay;
public class Adapter implements CatImpl,DogImpl{
private CatImpl cat;
private DogImpl dog;
public CatImpl getCat() {
return cat;
}
public void setCat(CatImpl cat) {
this.cat = cat;
}
public DogImpl getDog() {
return dog;
}
public void setDog(DogImpl dog) {
this.dog = dog;
}
@Override
public void catchMice() {
System.out.print("狗学");
cat.catchMice();
}
@Override
public void cry() {
System.out.print("猫学");
dog.cry();
}
}
package Adapter.BothWay;
public class Cat implements CatImpl{
@Override
public void catchMice() {
System.out.println("猫抓老鼠");
}
@Override
public void cry() {
}
}
package Adapter.BothWay;
public interface CatImpl {
public void catchMice();
public void cry();
}
package Adapter.BothWay;
public class Dog implements DogImpl{
@Override
public void cry() {
System.out.println("狗叫");
}
@Override
public void catchMice() {
}
}
package Adapter.BothWay;
public interface DogImpl {
public void cry();
public void catchMice();
}
package Adapter.BothWay;
public class Client {
public static void main(String[] args) {
Adapter adapter = new Adapter();
CatImpl cat = new Cat();
DogImpl dog = new Dog();
adapter.setCat(cat);
adapter.setDog(dog);
cat = (CatImpl) adapter;
cat.cry();
dog = (DogImpl) adapter;
dog.catchMice();
}
}
