标签:
设计模式
适配器模式
适配器模式(Adapter Pattern)是把一个类的接口变换成客户端所期待的另一种接口, 从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作, 又称为转换器模式, 变压器模式, 包装(Wrapper)模式(把已有的一些类包装起来, 使之有能满足需要的接口). 适配器共分两种适模式. 无论哪种适配器, 它的宗旨都是保留现有类所提供的服务, 向客户提供接口, 以满足客户的期望. 即在不改变原有系统的基础上, 提供新的接口服务.
对象适配器模式---在这种适配器模式中, 适配器容纳一个它包裹的类的实例. 在这种情况下, 适配器调用被包裹对象的物理实体.
设计原则
Java JDK中的适配器模式
与桥接模式和装饰者模式的区别
使用场合
实现代码
//电源基类 public abstract class AbsBasePower01 { private float power; private String unit = "V"; public AbsBasePower01(float power) { this.power = power; } public float getPower() { return power; } public void setPower(float power) { this.power = power; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } }
//220V电源接口 public interface IPower22001 { public void output220v(); }
//12V电源接口 public interface IPower1201 { public void output12v(); }
//12V电源接口 public interface IPower1201 { public void output12v(); }
//12V电源实现类 public class Power1201 extends AbsBasePower01 implements IPower1201 { public Power1201() { super(12); } public void output12v() { System.out.println("-------This is " + super.getPower() + super.getUnit() + " power-------"); } }
//对象适配器实现类 public class AdapterPower1201 implements IPower1201 { //待转换的对象 private final AbsBasePower01 basePower01; public AdapterPower1201(AbsBasePower01 basePower01) { this.basePower01 = basePower01; } public void output12v() { //获得外部电源值 float power = this.basePower01.getPower(); //进行电源转换 if(380 == power) power = power / 31.67f; else if(220 == power) power = power / 18.33f; else if(110 == power) power = power / 9.17f; else { System.out.println("-------不能适配电源-------"); return; } power = (int)(power * 10) / 10.0f; System.out.println("-------This is " + power + this.basePower01.getUnit() + " power-------"); } }
//类适配器实现 public class ApapterPower12Ext01 extends AbsBasePower01 implements IPower1201 { public ApapterPower12Ext01(AbsBasePower01 power) { super(power.getPower()); } public void output12v() { //获得外部电源值 float power = super.getPower(); //进行电源转换 if(380 == power) power = power / 31.67f; else if(220 == power) power = power / 18.33f; else if(110 == power) power = power / 9.17f; else { System.out.println("-------不能适配电源-------"); return; } power = (int)(power * 10) / 10.0f; System.out.println("-------This is " + power + super.getUnit() + " power-------"); } }
//客户端 public class ClienMain { public static void main(String[] args) { Power22001 power_220 = new Power22001(); power_220.output220v(); IPower1201 power_120 = new Power1201(); power_120.output12v(); System.out.println("\n -------适配器转换中"); IPower1201 adapter_power_12 = new AdapterPower1201(power_220); adapter_power_12.output12v(); System.out.println("\n -------适配器转换中"); IPower1201 adapter_power_12_ext = new ApapterPower12Ext01(power_220); adapter_power_12_ext.output12v(); } }
标签:
原文地址:http://www.cnblogs.com/jin12/p/5590505.html