---
title: "适配器模式"
author: "jzinfo"
date: "2009-12-27T23:59:48Z"
tags: []
categories: ["企业架构"]
slug: "untitled"
draft: false
lastmod: "2009-12-28T14:48:44Z"
id: 558012
url: "https://jzinfo.iteye.com/blog/558012"
---

在什么情况下使用适配器设计模式？

 

1\. 系统需要使用现有的类，而此类的借口不符合系统的需要

2\. 想要建立一个可以复用的类，用于与一些彼此之间没有太大关联的一些类，包括一些可能在将来引进的类一起工作。

3\. 在设计里，需要改变多个已有的子类的接口，如果使用类的适配器模式，就要针对每一个子类做一个适配器类，而这不太实际。

 

适配器模式结构上分为两种。一个是类的适配器模式结构，另外一个是对象的适配器模式结构。

 

类的适配器结构.主要是使适配器类继承自源类而同时实现目标角色的接口的类。 这个有一个弊端是，如果要更改源类的一个或者多个方法，就只好先做一个源类的子类，然后在子类中覆盖父类的方法，改变行为，然后再让适配器类(Adaptee)继承，从而实现适配。

 

先看类的适配器模式代码：

目标角色（Target）,这里使用一个接口来说明：

```
package com.longweir.adapter;

 
public interface Target {
	
	//这个方法在源类中有定义
	public void sampleOperation1();
	
	//这个方法在源类中没有定义
	public void sampleOperation2();
}
```

 

源角色类（Adaptee）

```
package com.longweir.adapter;


public class Adaptee {
	
	public void sampleOperation1()
	{
		//Todo something		
	}
	
}
```

 

这里我们需要将Adaptee和接口Target衔接起来，所以我们需要使用一个适配器类来实现这样的工作

Adapter：

```
package com.longweir.adapter;

public class Adapter extends Adaptee implements Target {
	
              //sampleOperation1已经在父类中有了实现
        

	public void sampleOperation2(){
		
		//TODO something here.
		
		}
	
}
```

 

 这样一来，我们就很好的将源角色的API和目标角色的API衔接在一起，进行了适配.

 

但是，当如果我们的源类和源的子类都同时要适配时，则此方法不可行。这时，我们可以考虑将源目标角色作为一个成员属性而委派到适配类中，并调用该成员的相关方法。 这个就是对象的适配器模式结构

 

以上代码不变 我们只改Adapter类即可。

```
package com.longweir.adapter;

public class Adapter implements Target {
	//源角色作为一个属性成员
	private Adaptee adaptee;
	
	//Constructor with the parameter
	public Adapter(Adaptee adaptee){
	    super();
	    this.adaptee=adaptee;	
	}
	
	//使用成员属性的方法实现接口方法
	public void sampleOperation1(){
	    adaptee.sampleOperation1();	
	}
	
	public void sampleOperation2(){
	   
	    //todo something herer	
	}
	
}
```

 

 

 先这样了，这个例子是拷贝的阎宏的书上的例子，下篇再谢谢关于缺省适配器的例子以及JAVA中使用适配器模式的说明