设计模式-06-适配器模式

来源:互联网 发布:python web麻瓜编程 编辑:程序博客网 时间:2024/05/22 13:09

本文参考自《设计模式-可复用面向对象的基础》,《Java与模式》,《模式-工程化实现及扩展》

一、作用

把一个类的接口变换成客户端所期待的另一种接口,从而使因接口不匹配而无法在一起工作的两个类能够在一起工作(Gang of four)。

二、角色

1.Target:客户端期望的新接口。
2.Adaptee:需要被适配的目标类型,比较老的类型。
3.Adapter:完成对Adaptee到Target的转化。

二、分类

1.类的适配器模式



2.对象的适配器模式


三、Code

1.ITarget

package com.jue.test;public interface ITarget {public void newRequest();}

2.Adaptee

package com.jue.test;public class Adaptee {public void oldRequest() {}}

3.类适配器

package com.jue.test;public class Adapter1 extends Adaptee implements ITarget {@Overridepublic void newRequest() {super.oldRequest();}}

4.对象适配器

package com.jue.test;public class Adapter2 implements ITarget {private Adaptee adaptee;public Adapter2(Adaptee adaptee) {this.adaptee = adaptee;}@Overridepublic void newRequest() {adaptee.oldRequest();}}

四、使用场景

1.想使用一个已经存在的类,而它的接口不符和新的需求。
2.(对象适配器)想要使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口。

原创粉丝点击