---
title: "设计模式（七）--适配器模式"
author: "henu_zhangyang"
date: "2018-01-09T21:32:49Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2018-01-09T21:51:44Z"
id: 2407293
url: "https://ihenu.iteye.com/blog/2407293"
---

**适配器模式**：将一个类的接口，转换成客户期望的另外一个接口，适配器将原本接口不兼容的类可以合作无间。

 

意图：不改变接口，但加入责任 

 

 

```
/**
 *暴露的公共接口
 * Created by Administrator on 2018/1/9.
 */
public interface Duck {
    void quack();
    void fly();
}
```

 

```
/**
 * 需要被适配的接口
 * Created by Administrator on 2018/1/9.
 */
public interface Turkey {
    void gobble();
    void fly();
}
```

 

```
/**
 * Created by Administrator on 2018/1/9.
 */
public class WildTurkey implements  Turkey {
    @Override
    public void gobble() {
        System.out.println("wildturkey is gobble");
    }

    @Override
    public void fly() {
        System.out.println("wildturkey is fly");
    }
}
```

 

```
/**
 * 适配器
 * Created by Administrator on 2018/1/9.
 */
public class TurkeyAdapter implements Duck {

    private Turkey turkey;

    public TurkeyAdapter(Turkey turkey) {
        this.turkey = turkey;
    }

    @Override
    public void quack() {
        turkey.gobble(); //这里进行适配
    }

    @Override
    public void fly() {
        turkey.fly();
    }
}
```

 

 

```
/**
 * Created by Administrator on 2018/1/9.
 */
public class TestAdapter {
    public static void main(String[] args) {
        Turkey wildTurkey = new WildTurkey();
        wildTurkey.gobble();

        /**
         * 这里进行适配
         * **/
        TurkeyAdapter turkeyAdapter = new TurkeyAdapter(wildTurkey);
        turkeyAdapter.quack();
        turkeyAdapter.fly();
    }
}
```