设计模式(三)–适配器模式
其他链接
JVM学习笔记(一)
JVM学习笔记(二)
JVM学习笔记(三)
JVM学习笔记(四)
(待更新…)
Java NIO
(待更新…)
设计模式(一)
设计模式(二)
设计模式(三)
设计模式(四)
(待更新…)
1. 适配器模式
1.1 介绍
适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种模式涉及到一个单一的类,该类负责加入独立的或不兼容的接口功能。适配器模式是属于结构型模式。
适配器有两种实现的方式:
- 类适配器
- 对象适配器
1.2 类适配器
类适配器用的是继承的方式,类适配器有一点缺点,对应一些只支持单继承的语言来说,类适配器只能做单一的适配工作。
代码实现
适配器接口
public interface Adapter{
//适配方法,Netline转Usb接口
public void NetlineToUsb();
}
适配器实现类
public class transfer extends Computer implements Adapter{
//转换器继承电脑类,实现适配接口
public void NetlineToUsb(){
System.out.println("转化处理");
super.ToUsb();
}
}
网线
public class Netline{
public void lineTo(Adapter Usbadapter){
System.out.println("插入网线口");
Usbadapter.NetlineToUsb()
}
}
电脑类
public class Computer{
public void ToUsb(){
System.out.println("插入USB口网线");
}
}
演示
public static void main(String[] args){
//创建电脑,网线,适配器
Computer c = new Computer();
Netline n = new Netline();
transfer t = new transfer();
/*
流程:
网线调用lineto,插入适配器中
适配器调用继承方法,插入到电脑中
*/
n.lineTo(t);
}
如图:
1.3对象适配器
对象适配器使用的是对象依赖的方式,不通过继承方式来实现。只需更改适配器实现类,让其使用对象的方式即可。
适配器实现类
public class transfer implements Adapter{
private Computer computer;
public transfer(Computer computer){
this.computer = computer;
}
public void NetlineToUsb(){
System.out.println("转化处理");
this.computer.ToUsb();
}
}
演示
public static void main(String[] args){
//创建电脑,网线,适配器
Computer c = new Computer();
Netline n = new Netline();
transfer t = new transfer(c);
n.lineTo(t);
}
1.4 对比
- 对象适配器优点:对象适配器能把不同的适配者传递给适配者,符合“里氏替换原则”