`
DanielHan
  • 浏览: 54453 次
  • 性别: Icon_minigender_1
  • 来自: 北京
博客专栏
074641d7-eb86-343f-a745-65a0f693edb5
设计模式
浏览量:7142
社区版块
存档分类
最新评论

设计模式-适配器模式

阅读更多
适配器模式(Adapter pattern)
适配器模式将某个类的接口转换成客户端期望的另一个接口表示,目的是消除由于接口不匹配所造成的类的兼容性问题。




电源基类
public abstract class Power {
	
	private float power;
	private String unit="V";
	
	public Power(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 IPower220 {
	public void output220();
}


220V电源
public class Power220 extends Power implements IPower220{

	public Power220(float power) {
		super(power);
	}

	@Override
	public void output220() {
		System.out.println(this.getPower()+this.getUnit()+"电源");
	}
}


12V电源接口
public interface IPower12 {
	public void output12();
}


12V电源
public class Power12 extends Power implements IPower12{

	public Power12(float power) {
		super(power);
	}

	@Override
	public void output12() {
		System.out.println(this.getPower()+this.getUnit()+"电源");
	}
}


对象适配器
对象适配器使用组合方法。
public class Adapter implements IPower12{
	//待转换电源
	private Power power;

	public Adapter(Power power){
		this.power=power;
	}
	/**
	 * description 
	 */
	@Override
	public void output12() {
		//转换为12v的过程
		System.out.println("12V电源");
	}
}


测试类:
public class Demo {
	public static void main(String[] args) {
		Power220 power220=new Power220(220);
		Adapter adapter =new Adapter(power220);
		adapter.output12();
	}
}


类适配器
类适配器使用继承方法。
public class Adapter extends Power implements IPower12{

	public Adapter(float power) {
		super(power);
	}

	@Override
	public void output12() {
		System.out.println("12V电源");
	}
}


测试类:
public class Demo {
	public static void main(String[] args) {
		Adapter adapter =new Adapter(220);
		adapter.output12();
	}
}

适配器模式主要用于系统的升级扩展,或者版本兼容性上。
  • 大小: 44.2 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics