---
title: "设计模式-适配器模式"
author: "DanielHan"
date: "2014-02-11T09:54:01Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2014-02-11T09:54:01Z"
id: 2013733
url: "https://danielhan.iteye.com/blog/2013733"
---

适配器模式（Adapter pattern）
适配器模式将某个类的接口转换成客户端期望的另一个接口表示，目的是消除由于接口不匹配所造成的类的兼容性问题。


![](http://dl2.iteye.com/upload/attachment/0093/7130/c357d41d-8331-3458-8c26-3fc2282e5918.png)

电源基类

```java

public abstract class Power {
	
	private float power;
	private String unit="V";
	
	public Power(float power){
		this.power=power;
	}
	
	public float getPower() {
		return power;
	}
	public void setPower(float power) {
		this.power = power;
	}
	public String getUnit() {
		return unit;
	}

	public void setUnit(String unit) {
		this.unit = unit;
	}
}

```


220V电源接口

```java

public interface IPower220 {
	public void output220();
}

```


220V电源

```java

public class Power220 extends Power implements IPower220{

	public Power220(float power) {
		super(power);
	}

	@Override
	public void output220() {
		System.out.println(this.getPower()+this.getUnit()+"电源");
	}
}

```


12V电源接口

```java

public interface IPower12 {
	public void output12();
}

```


12V电源

```java

public class Power12 extends Power implements IPower12{

	public Power12(float power) {
		super(power);
	}

	@Override
	public void output12() {
		System.out.println(this.getPower()+this.getUnit()+"电源");
	}
}

```


对象适配器
对象适配器使用组合方法。

```java

public class Adapter implements IPower12{
	//待转换电源
	private Power power;

	public Adapter(Power power){
		this.power=power;
	}
	/**
	 * description 
	 */
	@Override
	public void output12() {
		//转换为12v的过程
		System.out.println("12V电源");
	}
}

```


测试类：

```java

public class Demo {
	public static void main(String[] args) {
		Power220 power220=new Power220(220);
		Adapter adapter =new Adapter(power220);
		adapter.output12();
	}
}

```


类适配器
类适配器使用继承方法。

```java

public class Adapter extends Power implements IPower12{

	public Adapter(float power) {
		super(power);
	}

	@Override
	public void output12() {
		System.out.println("12V电源");
	}
}

```


测试类：

```java

public class Demo {
	public static void main(String[] args) {
		Adapter adapter =new Adapter(220);
		adapter.output12();
	}
}

```

适配器模式主要用于系统的升级扩展，或者版本兼容性上。