栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

设计模式——(8)适配器模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

设计模式——(8)适配器模式

第八章 适配器模式 1.1 适配器的定义

为什么需要适配器模式?

我们知道程序中的对象,是对象现实世界的抽象。

当现实中遇到如下情况时:使用美国制造的电脑在欧洲使用时,需要一个交流电的适配器。

适配器模式的定义:将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。

这里一个类的接口即欧洲壁式插座提供的电力接口,是三角插头,客户期望的另一个接口是笔记本电脑需要的接口。

适配器的类图如下图所示。

1.2 使用适配器模式

使用鸭子和火鸡来举例说明,客户期望的接口是鸭子,火鸡是被适配的接口。

首先定义一个客户期望的接口 Duck :

package headfirst.designpatterns.adapter;

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

定义一个被适配的接口 Turkey:

package headfirst.designpatterns.adapter;

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

再定义一个鸭子适配器类:TurkeyAdapter 类

package headfirst.designpatterns.adapter;

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();
		}
	}
}

定义一只具体的鸭子:MallardDuck

package headfirst.designpatterns.adapter;

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

定义一只具体的火鸡:

package headfirst.designpatterns.adapter;

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");
	}
}

进行测试:

package headfirst.designpatterns.adapter;


public class DuckTestDrive {
	public static void main(String[] args) {
		Duck duck = new MallardDuck();

		Turkey 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();
	}
}

输出:

The Turkey says...
Gobble gobble
I'm flying a short distance

The Duck says...
Quack
I'm flying

The TurkeyAdapter says...
Gobble gobble
I'm flying a short distance
I'm flying a short distance
I'm flying a short distance
I'm flying a short distance
I'm flying a short distance

Process finished with exit code 0
1.3 总结
  • 当要使用一个现有的类而其接口并不符合你的需要时,就可以使用适配器。
  • 适配器改变接口以符合客户期望
  • 适配器将一个对象包装起来以改变其接口;装饰者将一个对象包装起来以增加新的行为和责任。
参考

[1] Freeman E. Head First 设计模式[M] 中国电力出版社.
[2] 菜鸟教程

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/948858.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号