atwood-pan

 

09-设计模式——适配器模式

设计模式——适配器模式

适配器模式Adapter ==> 解决兼容性问题

模式定义:

将一个类的接口转换成客户希望的另一个接口

Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作

LKs60S.png

Class Diagram

LKyLb8.png

对象适配器模式

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   JavaCoderPan  阅读(14)  评论(0编辑  收藏  举报  

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南

导航

统计

点击右上角即可分享
微信分享提示