---
title: "设计模式之适配器模式"
author: "GLC"
date: "2015-08-04T21:26:06Z"
tags: []
categories: ["企业架构"]
slug: "untitled"
draft: false
lastmod: "2015-08-04T21:28:53Z"
id: 2232850
url: "https://glc.iteye.com/blog/2232850"
---

设计模式之适配器模式

作用：为了将某个类的接口转换成客户端期望的另一个接口，消除由于接口不匹配所造成的类的兼容性问题。
按适配的内容分为三类：
1、类的适配器模式
2、对象的适配器模式
3、接口的适配器模式

1、类的适配器模式：一个有方法的类，等待目标接口适配；通过Adapter类，将等待适配的类的方法扩展到目标接口中。
等待适配的类

```java

public  class Source{
	public void method1(){
		System.out.println(“this is original method”);
	}
}


```



目标接口

```java

public interface Targetable{
	//与原类方法相同
	public void method1();

	public void method2();
}

```


适配类

```java

public class Adapter extends Source implements Targetable{
	//重写接口中剩下的方法
	public void method2(){
		System.out.println(“this is the targetable method”);
	}
}

```


最后调用，通过实例化Adapter类，便可以调用等待适配类的方法了。

2、对象的适配器模式
基本思路跟前面的相同，只是这里不再继承Source类，而是持有待适配的类实例;来达到兼容和适配。
修改Adapter类

```java


public class Adapter implements Targetable{
	private Source source;
	
	public Adapter(Source source){
		super();
		this.source = source;
	}
	
	public void method2(){
		System.out.println(“this is the targetable method!”);
	}

	public void method1(){
		source.method1();
	}
}



```

最后的调用实现过程跟第一种一样。

3、接口的适配器模式

它使用的情况比如：一个接口中有太多的抽象方法，当我们要使用这个接口时，
便需要实现接口中所有的抽象方法。但大多情况下、接口中的抽象方法我只需要其中一些。
所以、为了解决这个问题，我们借助一个抽象类、该抽象类实现了该接口，然后实现所有的方法。我们使用时、通过继承该抽象类，重写我们需要的方法就达到了想要的目的。

等待适配的接口

```java


public interface Sourceable{
	public void method1();
	public void method2();
	…
}


```

自己写抽象类

```java


public abstract class Wrapper implements Sourceable{
	public void method1(){}
	public void method2(){}
	…
}

public class SourceSub1 extends Wrapper{
	public void method1(){
		System.out.println(“the sourceable interface’s first ”);
	}
}

public class SourceSub2 extends Wrapper{
	public void method2(){
		System.out.println(“the source able interface’s second”);
	}
}


```

最后使用时，只需要实例化实现具体方法的类；调用相应的方法即可。
本想借此机会、学习画类图来呈现结果，但最后还是没能做到。以后希望自己能快速学习类图来展现和表达吧。