您当前的位置: 首页 > 

宝哥大数据

暂无认证

  • 4浏览

    0关注

    1029博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

23种设计模式05---适配器模式

宝哥大数据 发布时间:2017-04-01 08:57:22 ,浏览量:4

前言

本文开始,将开始学习7种结构型模式:适配器模式、装饰模式、代理模式、外观模式、桥接模式、组合模式、享元模式。

其中对象的适配器模式是各种模式的起源

这里写图片描述

一、适配器模式 1.1、类的适配器模式

这里写图片描述

更形象的展示:

这里写图片描述

代码展示
public class Source {
    public void srcMethod() {
        System.out.println("我连接usb接口");
    }
}

/**
 *  目标接口 Targetable
 */
public interface Targetable {
    /** 与源类的方法相同 */
    public void srcMethod();

    /** 新方法 */
    public void targetMethod();
}

//适配器,他要具有新的输出口和旧的输出口功能, 使用继承(继承只能是单继承), 实现另一个接口
public class Adapter extends Source implements Targetable{
    @Override
    public void targetMethod() {
        System.out.println("我连接串口");
    }
}
调用方法:
public class Test {
    public static void main(String[] args) {
        //父类/父接口引用指向子类对象
        Targetable targetable = new Adapter();
        //连接usb时, 可以使用与源类的相同方法
        targetable.srcMethod();
        //如果连接串口, 使用自己的方法
        targetable.targetMethod();
    }
}
1.2、对象的适配器模式

目标接口不变, 适配器类持有源类的对象

public class Adapter  implements Targetable{
    private Source source;
    public Adapter(Source source) {
        this.source = source;
    }

    @Override
    public void targetMethod() {
        System.out.println("我连接串口");
    }

    @Override
    public void srcMethod() {
        source.srcMethod();
    }
}
1.3、接口的适配器模式
关注
打赏
1587549273
查看更多评论
立即登录/注册

微信扫码登录

0.0718s