---
title: "设计模式之适配器模式&外观模式"
author: "hwaspf"
date: "2009-09-28T15:07:54Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2009-09-28T15:16:37Z"
id: 479504
url: "https://hwaspf.iteye.com/blog/479504"
---

适配器模式将一个类的接口，转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。涉及到得OO原则：使用对象组合，以修改的接口包装被适配者。

```java
public interface Duck {
	public void quack();
	public void fly();
}

```



```java
public interface Turkey {
	public void gobble();
	public void fly();
}

```



```java
public class WildTurkey implements Turkey {
	public void gobble() {
		System.out.println("Gobble gobble");
	}
 
	public void fly() {
		System.out.println("I'm flying a short distance");
	}
}
```



```java
public class TurkeyAdapter implements Duck {
	Turkey turkey;
 
	public TurkeyAdapter(Turkey turkey) {
		this.turkey = turkey;
	}
    
	public void quack() {
		turkey.gobble();
	}
  
	public void fly() {
		for(int i=0; i < 5; i++) {
			turkey.fly();
		}
	}
}
```



```java
public class MallardDuck implements Duck {
	public void quack() {
		System.out.println("Quack");
	}
 
	public void fly() {
		System.out.println("I'm flying");
	}
}
```



```java
public class DuckTestDrive {
	public static void main(String[] args) {
		MallardDuck duck = new MallardDuck();
 
		WildTurkey turkey = new WildTurkey();
		Duck turkeyAdapter = new TurkeyAdapter(turkey);
   
		System.out.println("The Turkey says...");
		turkey.gobble();
		turkey.fly();
 
		System.out.println("\nThe Duck says...");
		testDuck(duck);
  
		System.out.println("\nThe TurkeyAdapter says...");
		testDuck(turkeyAdapter);
	}
 
	static void testDuck(Duck duck) {
		duck.quack();
		duck.fly();
	}
}
```


上面的例子为适配器模式，外观模式与适配器模式类似，但是外观模式是提供一个统一的接口，用来访问子系统中的一群接口。外观定义了一个高层接口，让子系统更容易使用。简单来说，外观模式就是将很多动作封装在一个方法里面，而不是像适配器模式一样，只封装了一个动作。