适配器模式学习

适配器模式

适配器模式(Adapter Pattern):将一个类的接口转换成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

oo设计原则

  • 面向接口编程
  • 封装变化
  • 多用组合,少用继承
  • 对修改关闭,对扩展开放

适配器模式使用案列一

public class AdaperPattern {

	public static void main(String[] args) {
		// 电源A
		PowerA powerA = new PowerAImpl();
		// work(powerA);

		// 电源B
		PowerB powerB = new PowerBImpl();
		PowerAdapter adapter = new PowerAdapter(powerB);
		work(adapter);
	}

	public static void work(PowerA powerA) {
		System.out.println("正在链接电源。。。");
		powerA.insert();
		System.out.println("工作结束");
	}
}

// 接口A
interface PowerA {
	public void insert();
}

// 接口A实现类
class PowerAImpl implements PowerA {
	@Override
	public void insert() {
		System.out.println("电源A开始工作。");
	}
}

// 现在新出了一个电源B
// 问题:我想用电源B,但又不想修改原来的(AdaperPattern类)代码,怎么办?

// 电源适配器类
class PowerAdapter implements PowerA {
	private PowerB powerB;// 被适配对象

	public PowerAdapter(PowerB powerB) {
		this.powerB = powerB;
	}

	@Override
	public void insert() {
		powerB.connect();
	}
}

// 接口B  
interface PowerB {
	public void connect();
}

// 接口B实现类
class PowerBImpl implements PowerB {
	@Override
	public void connect() {
		System.out.println("电源B开始工作。");
	}
}

适配器模式使用二

interface Animal{
	public void run();
	public void cry();
	public void sing();
	public void laugh();
}

// 没有适配器类时,我们虽然只关注run方法,但是实现接口必须实现所有的抽象方法
class Dog implements Animal{

	@Override
	public void run() {
		System.out.println("我喜欢跑。。");
	}
	public void cry() {}
	public void sing() {}
	public void laugh() {}

}

// 增加抽象类,对接口中的方法作了空实现,这样子类在继承时就不用实现接口不得不实现接口中的全部方法
abstract class AnimalFunction implements Animal{
	public void run() {};
	public void cry() {};
	public void sing() {};
	public void laugh() {};
}

// 通过增加抽象类,通过继承,现在我们不用实现接口,而必须实现全部方法了
class Animal extends AnimalFunction{
	@Override
	public void run() {
		System.out.println("我喜欢跑");
	}
}
posted on 2019-05-13 17:11  行之间  阅读(382)  评论(0编辑  收藏  举报