`

设计模式之Adapter

 
阅读更多

        Adapter设计模式

 

        在设计模式里,适配器模式(Adapter pattern)是将一个类的接口转换成用户所期待的。一个适配使得因接口不兼容而不能在一起的工作的类工作在一起。做法是将有别与自己的接口包裹在一个已存在的类中。

 

        如果你有一个存在的系统需要插入一个新的类库,但是新的类库并不能匹配你写的系统,如下图:   

 


         现在你不想更改存在的旧系统,新的类库也不能修改,这时候我们就需要写一个适配器了,用适配器来适配新类库的接口。如下图:



         用了适配器后的整个系统如下图:



        现实生活中也有很多适配器的例子,比如电源适配器和适用于苹果笔记本的各种转换器。电源适配器将家用的220v电压变成PC或者手机能使用的电压。  

  

        适配器模式属于结构型模式,实现适配器模式有两种方式:继承(inheritance,is-a关系)和组合(composition,has-a关系)。分别对应类适配器模式和对象适配器模式。

 

        1.类适配器模式(继承)

          这种的UML类图如下:



           对应的实现代码如下:

package xj.pattern.adapter;

interface Target{
	public void request();
}

//被适配对象
class Adaptee{
	public void specificRequest(){
		System.out.println("现在使用的电压是220V!");
	}
}

//适配器对象
class Adapter extends Adaptee implements Target{

	@Override
	public void request() {
		super.specificRequest();
		System.out.println("电源电压转换中。。。");
		System.out.println("转换成110V......");
	}
	
}

public class Client1 {
	
    public static void main(String[] args) {
		
    	Target target = new Adapter();
    	target.request();
	}
}

 

        2.对象适配器模式(组合)

          这种的UML类图如下:

 

 
         这种结构的实现代码如下:

     

interface Target{
	public void request();
}

//被适配对象
class Adaptee{
	
	public void specificRequest(){
		System.out.println("现在使用的电压是220V!");
	}
}

//适配器对象
class Adapter implements Target{
	
	private Adaptee adaptee;

	public Adapter(Adaptee adaptee) {
		this.adaptee = adaptee;
	}

	public Adaptee getAdaptee() {
		return adaptee;
	}

	public void setAdaptee(Adaptee adaptee) {
		this.adaptee = adaptee;
	}

	@Override
	public void request() {
		adaptee.specificRequest();
		System.out.println("电源电压转换中。。。");
		System.out.println("转换成110V......");
	}
	
}

public class Client2 {
	
	public static void main(String[] args) {
		
		Adaptee adaptee = new Adaptee(); //类似于Android中的数据源:ArrayList<Entity>
		Target target = new Adapter(adaptee); //类似于Android中的ArrayListAdapter;
		target.request();
	}
	
}

 

        Gof23定义了两种Adapter模式的实现结构:类适配器和对象适配器。但类适配器采用"多继承"的实现方式带来了不良的高耦合,所以一般不推荐使用。对象适配器采用"对象组合"的方式,更符合松耦合的精神。

 

        Adapter模式本身要求我们尽可能的使用"面向接口的编程"风格,这样才能在后期很方便的适配。

  • 大小: 19.1 KB
  • 大小: 5 KB
  • 大小: 20.3 KB
  • 大小: 96.4 KB
  • 大小: 42.6 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics