09-设计模式——适配器模式
设计模式——适配器模式
适配器模式Adapter ==> 解决兼容性问题
模式定义:
将一个类的接口转换成客户希望的另一个接口
Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作
Class Diagram
对象适配器模式
package com.example.designpatterns.adapter.v1;
/**
* @program: DesignPatterns
* @description: 对象适配器模式 V1
* 对象使用组合
* @author: Coder_Pan
* @create: 2022-04-13 15:23
**/
public class AdapterTest1 {
public static void main(String[] args) {
Adaptee adaptee = new Adaptee();
Target adapter = new Adapter( adaptee );
int i = adapter.output5V();
System.out.println(i);
}
}
class Adaptee{
public int output22V(){
return 220;
}
}
interface Target {
/**
* 目标接口电压
* @return
*/
int output5V();
}
class Adapter implements Target{
/**
* 组合方式
* @return
*/
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public int output5V() {
int i = adaptee.output22V();
// .....复杂的业务逻辑
System.out.println(String.format("原始电压:%d v -> 输出电压:%d v",i,5));
return 5;
}
}
类适配器模式
package com.example.designpatterns.adapter.v2;
/**
* @program: DesignPatterns
* @description: 类适配器模式 V2
* 类使用继承
* @author: Coder_Pan
* @create: 2022-04-13 15:24
**/
public class AdapterTest2 {
public static void main(String[] args) {
System.out.println("类适配器模式");
Adapter adapter = new Adapter();
//不符合最少知道原则,对接口有污染
adapter.output22V();//这是不符合的!!!这是类适配器的缺点
adapter.output5V();
}
}
/**
* 原始类 =》 Adaptee
*/
class Adaptee{
public int output22V(){
return 220;
}
}
/**
*
*/
interface Target {
/**
* 原始类 ==> 转换的目标电压
* @return
*/
int output5V();
}
/**
* 通过继承extends方式
*/
class Adapter extends Adaptee implements Target{
@Override
public int output5V() {
int i = output22V();
// .....复杂的业务逻辑
System.out.println(String.format("原始电压:%d v -> 输出电压:%d v",i,5));
return 5;
}
}
posted on 2022-04-13 15:44 JavaCoderPan 阅读(19) 评论(0) 收藏 举报 来源


浙公网安备 33010602011771号