适配器模式(java语言实现)

来源:互联网 发布:淘客cms源码带优惠券 编辑:程序博客网 时间:2024/06/05 16:21

定义

适配器模式将一个类的接口,转换成客户期望的另一个接口。 使得原本由于接口不兼容的而不能在一起工作的那些类可以在一起工作。而且不用修改原适配者类的代码。 wiki: https://en.wikipedia.org/wiki/Adapter_pattern An adapter helps two incompatible interfaces to work together. This is the real world definition for an adapter. Interfaces may be incompatible but the inner functionality should suit the need. The Adapter design pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients.

组合模式

这里写图片描述

TwoPlugAdapter.java

package com.immoc.pattern.adapter;/* * 二相转三相的插座适配器 */public class TwoPlugAdapter implements ThreePlugIf {    private GBTwoPlug plug;    public TwoPlugAdapter(GBTwoPlug plug){        this.plug = plug;    }    @Override    public void powerWithThree() {        System.out.println("通过转化");        plug.powerWithTwo();    }}

继承模式

这里写图片描述
TwoPlugAdapterExtends.java

package com.immoc.pattern.adapter;/* * 采用继承方式的插座适配器 */public class TwoPlugAdapterExtends extends GBTwoPlug implements ThreePlugIf {    @Override    public void powerWithThree() {        System.out.print("借助继承适配器");        this.powerWithTwo();    }}

Client

NoteBook.java

package com.immoc.pattern.adapter;public class NoteBook {    private ThreePlugIf  plug;    public NoteBook(ThreePlugIf plug){        this.plug = plug;    }    //使用插座充电    public void charge(){        plug.powerWithThree();    }    public static void main(String[] args) {        GBTwoPlug two =  new GBTwoPlug();        ThreePlugIf three = new TwoPlugAdapter(two);        NoteBook nb = new NoteBook(three);        nb.charge();        three = new TwoPlugAdapterExtends();        nb = new NoteBook(three);        nb.charge();    }}

优点

透明
通过适配器,客户端可以调用同一接口,因而对客户端来说是透明的。
这样更加简单、直接、紧凑。
重用
复用了现存的类,解决了现存类和复用环境要求不一致的情况。
低耦合
将目标类和适配者类解耦,通过一如一个适配器重用适配者类,
无需修改原有代码(遵循开闭原则)

0 0
原创粉丝点击