设计模式--适配器
今天说说设计模式中的适配器模式。举例来说,适配器模式,模式如其名。就是用适配器来适配原来的接口。
也就等同于原来220w的插销要插到440W或者110W的插座。要是直接插上要嘛冒黑烟要嘛没效果。为了要让插销能正常工作,这时候我们就需要变压器了。
适配的接口
package adapter;public interface Target {public void request();}
我们的插头
package adapter;public class Adaptee {public void specificRequest() {System.out.println("Adaptee TODO");}}
我们的适配器。就是变压器了
package adapter;public class Adapter implements Target {private final Adaptee fAdaptee;public Adapter(Adaptee adaptee) {super();fAdaptee = adaptee;}/*** 这个就是变压的具体过程了 */public void request() {fAdaptee.specificRequest();}}
package adapter;public class Client {private final Target fTarget;public Client(Target target) {super();fTarget = target;}public void useAdapter() { fTarget.request();}public static void main(String[] args) {Adaptee adaptee = new Adaptee();Adapter adapter = new Adapter(adaptee);Client client = new Client(adapter);client.useAdapter();}}
将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。(GoF)
页:
[1]