Java设计模式(9) —— 适配器

来源:互联网 发布:日本网络制式 编辑:程序博客网 时间:2024/06/05 19:26

Adapter

 

Intent
Convert the interface of a class into another interface clients expect.

Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
You want to use an existing class, and its interface does not match the one you need.

How to
Object Adapter
Class Adapter

Target
defines the domain-specific interface that Client uses.
Client
collaborates with objects conforming to the Target interface.
Adaptee
defines an existing interface that needs adapting.
Adapter
adapts the interface of Adaptee to the Target interface.

Known cases
Use third-party lib, but it doesn't satisfy the interface clients expect.

UML

对象适配器

类适配器

 

代码:

对象适配器

类适配器

 

区别:

(1)在Java中不允许多重继承,所以有些情况下必须得用“对象适配器”;比如:一个Adapter要实现一个抽象类的接口,而Adaptee也是一个类,这只能用“对象适配器”。

(2)对象适配器比类适配器更灵活,可以为对象适配器配置不同子类的Adaptee