定义:适配器模式将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。
适配器(Adapter)分为“对象(Object)”适配器和“类(Class)”适配器两种。
在类适配器中,适配器继承了目标(Target)和被适配者(Adaptee);而对象适配器中,适配器利用组合的方式将请求传送给被适配者。
实例:
让List类型支持枚举类型
public class ListEnumeration implements Enumeration {
private List list;
public ListEnumeration(List al) {
this.list = al;
}
public boolean hasMoreElements() {
return list.iterator().hasNext();
}
public Object nextElement() {
return list.iterator().next();
}
}
外观模式提供了一个统一的接口,用来访问子系统中的一群接口。外观定义了一个高层接口,让子系统更容易使用。
结构图如下:
public class Power {
public void connect() {
System.out.println("The power is connected.");
}
public void disconnect() {
System.out.println("The power is disconnected.");
}
}
// 主板
public class MainBoard {
public void on() {
System.out.println("The mainboard is on.");
}
public void off() {
System.out.println("The mainboard is off.");
}
}
// 硬盘
public class HardDisk {
public void run() {
System.out.println("The harddisk is running.");
}
public void stop() {
System.out.println("The harddisk is stopped.");
}
}
// 操作系统
public class OperationSystem {
public void startup() {
System.out.println("The opertion system is startup.");
}
public void shutdown() {
System.out.println("The operation system is shutdown.");
}
}
// 计算机外观
public class Computer {
private Power power;
private MainBoard board;
private HardDisk disk;
private OperationSystem system;
public Computer(Power power, MainBoard board, HardDisk disk, OperationSystem system) {
this.power = power;
this.board = board;
this.disk = disk;
this.system = system;
}
public void startup() {
this.power.connect();
this.board.on();
this.disk.run();
this.system.startup();
}
public void shutdown() {
this.system.shutdown();
this.disk.stop();
this.board.off();
this.power.disconnect();
}
}