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

定义

适配器模式将一个类的接口,转换成客户期望的另一个接口。 使得原本由于接口不兼容的而不能在一起工作的那些类可以在一起工作。而且不用修改原适配者类的代码。 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值