设计模式之适配器模式

来源:互联网 发布:mac os x10.7.5下载 编辑:程序博客网 时间:2024/04/28 03:46

适配器模式(Adapter):将一个类的接口转换成客户端(client)希望的另外一个接口。Adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
Convert the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

适配器
这个有类adaptee方法method1()和method2()继承自ownInterface接口,现在有一个接口target有三个方法,需要用到method1()或者method2(),为了不造成耦合,需要一个适配器adapter将adaptee进行适配(java中有直接继承adaptee和 委托 方法),这样client就可以通过target调用adaptee的方法或者是自己实现的another

适配器模式分为类适配器和对象适配器.
类适配器的实现就是通过继承adaaptee实现适配,对象适配器就是用委托的方式实现适配

原始类

// 原始类public class Adaptee implements OwnInterface {    public void method1() {        System.out.println("原有功能1");    }    public void method2() {        System.out.println("原有功能2");    }}
// 目标接口,或称为标准接口public interface Target {    public void method1();    public void method2();    public void method3();}// 自己的实现public class Another implements Target {    public void method1() {        System.out.println("自己实现的功能1");    }    public void method2() {        System.out.println("自己实现的功能2");    }    public void method3() {        System.out.println("自己实现的功能3");    }}

类适配器

public class Adapter extends Adaptee implements Target{    public void method1() {        super.method1();    }    public void method2() {        super.method2();    }    public void method3() {        System.out.println("自己实现的功能1");    }}

对象适配器

public class Adapter implements Target{    //委托或者代理    private Adaptee adaptee = new Adaptee();    public void method1() {        this.adaptee.method1();    }    public void method2() {        this.adaptee.method2();    }    public void method3() {        System.out.println("自己实现的功能1");    }}

client类

public class Client {    public static void main(String[] args) {        // 使用普通功能类        Target another= new Another();        another.method1();        // 使用特殊功能类,即适配类,        // 需要先创建一个被适配类的对象作为参数        Target adapter = new Adapter();        adapter.method1();    }}
0 0
原创粉丝点击