设计模式之适配器模式(Adapter)

来源:互联网 发布:dnf武器数据库 编辑:程序博客网 时间:2024/06/05 04:17

设计模式之适配器模式(Adapter):

将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

适配器模式(Adappter)结构图:


源代码:

Target(这是客户所期待的接口,目标是可以是具体的或者抽象的类,也可以是接口)

class Target{public void Request(){System.out.println("普通请求!");}}

Adaptee(需要适配的类)

class Adaptee{public void SpecificRequest(){System.out.println("特殊请求!");}}

Adapter(通过在内部包装一个adaptee对象,将源接口转换成目标接口)

class Adapter extends Target{private Adaptee adaptee = new Adaptee();@Overridepublic void Request(){adaptee.SpecificRequest();}}

客户端代码:

public class test{public static void main(String[] args){Target target = new Adapter();target.Request();}}

适配器模式的应用场景:

在想使用一个已经存在的类时,它的方法和你要求的不相同时,就应该考虑用适配器。一般在后期维护时,在双方都不太容易修改的时候再使用适配器模式。





0 0