适配器设计模式(Adapter Pattern)

来源:互联网 发布:如何玩转linux 编辑:程序博客网 时间:2024/04/30 20:37

GOF设计模式
Adapter Pattern
适配器设计模式

适配器模式比喻

• 在朋友聚会上碰到了一个美女Sarah,从香港来的,可我不会说粤语,她不会说普通话,只好求助于我的朋友kent了,他作为我和Sarah之间的Adapter,让我和Sarah可以相互交谈了(也不知道他会不会耍我)

• 适配器(变压器)模式:把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口原因不匹配而无法一起工作的两个类能够一起工作。适配类可以根据参数返还一个合适的实例给客户端。

1.类的适配器

public interface Telephone {    public void tel();}

public class Socket {    public static void charge(){        System.out.println("我能充电!");    }}

public class MyAdapter extends Socket implements Telephone {    @Override    public void tel() {        super.charge();    }}

public class Test {    public static void main(String[] args) {        MyAdapter a=new MyAdapter();        a.tel();    }}

2.对象的适配器

public interface Telephone2 {    public void tel2();}


public class Socket2 {    public static void charge2(){        System.out.println("我能充电!");    }}

public class MyAdapter2 implements Telephone2{    private Socket2 socket2=new Socket2();    @Override    public void tel2() {        socket2.charge2();    }}

public class Test2 {    public static void main(String[] args) {        MyAdapter2 a=new MyAdapter2();        a.tel2();    }}


0 0
原创粉丝点击