Java设计模式----适配器模式(承上启下)

适配器模式

描述

适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。

分类

适配器可以分为两种: 类适配器 对象适配器

背景

此篇通过电压为例 现在有300V电压源 但是家居常用电压是220V 此时我们就需要适配器来对电压进行适配 从而是用户进行使用

类适配器完成适配

UML类图
在这里插入图片描述

适配源(300V电压源)

public class Adaptee {

    public void method1() {
        System.out.println("method1:现有300V电压");
    }

    public void method2() {
        System.out.println("method2:现有300V电压");
    }
}

提供给用户的接口 (电压通道1 电压通道2)

public interface Target {
    void targetMethod1();

    void targetMethod2();
}

类适配器 对电压进行适配 300V-220V

public class Adapter extends Adaptee implements Target {

    @Override
    public void targetMethod1() {
        method1();
        System.out.println("电压通道1现在已经适配为220V电压");
    }

    @Override
    public void targetMethod2() {
        method2();
        System.out.println("电压通道2现在已经适配为220V电压");
    }
}

用户调用电压通道用电

public class Test {

    public static void main(String[] args) {
        Target target = new Adapter();
        target.targetMethod1();
        target.targetMethod2();
    }
}

method1:现有300V电压
电压通道1现在已经适配220V电压
method2:现有300V电压
电压通道2现在已经适配220V电压

对象适配器完成适配

UML类图
在这里插入图片描述

适配源(300V电压源)

public class Adaptee {

    public void method1() {
        System.out.println("method1:现有300V电压");
    }

    public void method2() {
        System.out.println("method2:现有300V电压");
    }
}

提供给用户的接口 (电压通道1 电压通道2)

public interface Target {

    void targetMethod1();

    void targetMethod2();
}

类适配器 对电压进行适配 300V-220V

public class Adapter implements Target {

    private Adaptee adaptee;

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

    @Override
    public void targetMethod1() {
        adaptee.method1();
        System.out.println("电压通道1现在已经适配220V电压");
    }

    @Override
    public void targetMethod2() {
        adaptee.method2();
        System.out.println("电压通道2现在已经适配220V电压");
    }
}

用户调用电压通道用电


public class Test {

    public static void main(String[] args) {
        Target target = new Adapter();
        target.targetMethod1();
        target.targetMethod1();
    }
}

method1:现有300V电压
电压通道1现在已经适配220V电压
method1:现有300V电压
电压通道1现在已经适配220V电压
发布了19 篇原创文章 · 获赞 6 · 访问量 1973

猜你喜欢

转载自blog.csdn.net/qq_42252844/article/details/104512481
今日推荐