适配器模式

xiaoxiao2021-02-28  32

适配器模式

(1)定义:因某些原因不能在一起工作的两个类可以协同工作,目的是兼容性。

(2)分类:

①类适配器模式

1.关系图:

2.优点:适配器集继承了源数据类的方法,可以重写其中的方法,增加灵活性

3.缺点:要求输出数据的必须是接口,具有一定局限性;违反合成复用原则

4.代码

/** * 这是个用户类 * 使用适配器 * 可以想象成手机 * @author Administrator * */ public class Client { public void charge(Destination power) { if(power.adaptedPower()==5) { System.out.println("适配电源成功"); } else { System.out.println("适配电源失败"); } } } /** * 这里是适配器类 * 将电压从220不合适的电压转换成5V合适电压的地方 * @author Administrator * */ public class Adapter extends Source implements Destination{ @Override public int adaptedPower() { // TODO Auto-generated method stub System.out.println("获取原始电压"); int sourcePower = originPower(); System.out.println("开始转换电压"); int adaptedPower = sourcePower/44; System.out.println("输出转变后的电压"); return adaptedPower; } } /** * 这里假设充电的电源为220V * @author Administrator * */ public class Source { int source = 220; public int originPower() { System.out.println("原始电压:"+source); return source; } } /** * 通过这个接口得到适配器转换后的电压 * @author Administrator * */ public interface Destination { public int adaptedPower(); }

②对象适配器模式

1.关系图:

2.优点:

尽量使用关联关系代替继承关系,在这点上符合合成复用原则,解耦

解决了必须继承源数据类和目的数据必须是接口的问题,降低成本,增加灵活性

3.代码

/** * 通过这个接口得到适配器转换后的电压 * @author Administrator * */ public interface Destination { public int adaptedPower(); } /** * 这里是适配器类 * 将电压从220不合适的电压转换成5V合适电压的地方 * @author Administrator * */ public class Adapter implements Destination{ Source source; public Adapter(Source source) { // TODO Auto-generated constructor stub this.source=source; } @Override public int adaptedPower() { // TODO Auto-generated method stub if(source!=null) { System.out.println("获取原始电压"); int sourcePower = source.originPower(); System.out.println("开始转换电压"); int adaptedPower = sourcePower/44; System.out.println("输出转变后的电压"); return adaptedPower; } else { System.out.println("没有电源"); } return 0; } } /** * 这里假设充电的电源为220V * @author Administrator * */ public class Source { int source = 220; public int originPower() { System.out.println("原始电压:"+source); return source; } } /** * 通过这个接口得到适配器转换后的电压 * @author Administrator * */ public interface Destination { public int adaptedPower(); }

 

转载请注明原文地址: https://www.6miu.com/read-2596088.html

最新回复(0)