设计模式之适配器模式

参考博文:https://www.cnblogs.com/java-my-life/archive/2012/04/13/2442795.html   侵权必删

适配器模式  Adapter

2019-06-24 09:15:08

什么是适配器:将一个接口转换成客户端期望地接口,或认为将原接口转换成目标接口,使得在不修改接口的情况下,实现对原接口的复用和功能扩展。

适用性:需要将原接口转换为目标接口的场合。

适配器分类:类适配器、对象适配器、缺省适配器

类适配器:实现目标接口,继承有源接口。

     特点:通过静态继承的方式实现,只能针对继承父类进行适配。

对象适配器:实现目标接口,组合原接口。

     特点:通过动态组合的方式实现,通过多态的机制可以对原接口的所有子类进行适配。

缺省适配器:比较特殊的适配器,用于不需要实现所有接口方法的场合。

适配器成员:原接口、目标接口、适配器(implements目标接口,且需要源接口的具体实现(通过继承或组合的方式获得))、客户端;

适配器基本代码:

类适配器:

/**
 * 目标接口
 */
public interface Target {
    public void opration1();
    public void opration2();
}
/**
 * 源接口
 */
public class Adaptee {
    public void opration1(){
        System.out.println("opration 1 from Adaptee.");
    }
}
/*
    类适配器
*/
public class Adapter extends Adaptee implements Target {
    @Override
    public void opration2() {
        System.out.println("opration 2 from Adapter.");
    }

    public static void main(String[] args) {
        Target t = new Adapter();
        t.opration1();
        t.opration2();
    }
}


//结果
opration 1 from Adaptee.
opration 2 from Adapter.

 

对象适配器

/**
 * 目标接口
 */
public interface Target {
    public void opration1();
    public void opration2();
}
/**
 * 源接口
 */
public class Adaptee {
    public void opration1(){
        System.out.println("opration 1 from Adaptee.");
    }
}
public class Adapter implements Target {
    private Adaptee adaptee;

    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void opration1() {
        adaptee.opration1();
    }

    @Override
    public void opration2() {
        System.out.println("opration 2 from Adapter.");
    }

    /*
        测试代码
     */
    public static void main(String[] args) {
        Target t = new Adapter(new Adaptee());//组合的方式,传入Adaptee引用
        t.opration1();
        t.opration2();
    }
}

缺省模式:

适配器(抽象函数)用空方法实现接口,客户端继承适配器(抽象函数)。

 

posted @ 2019-06-24 09:45  由走啦啦啦  阅读(108)  评论(0编辑  收藏  举报