前言
本文开始,将开始学习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();
}
}