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

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

对象适配器

Java设计模式(9) —— 适配器_第1张图片

类适配器

Java设计模式(9) —— 适配器_第2张图片

 

代码:

对象适配器

public interface Shape { void draw(); } public class LineAdapter implements Shape { private LineAdaptee delegate; public LineAdapter(LineAdaptee adaptee) { delegate = adaptee; } public void draw() { delegate.drawLine(); } } public class LineAdaptee { public void drawLine() { // todo } }

类适配器

public interface Shape { void draw(); } public class LineAdapter extends LineAdaptee implements Shape { public void draw() { drawLine(); } } public class LineAdaptee { public void drawLine() { // todo } }

 

区别:

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

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

你可能感兴趣的:(Java设计模式(9) —— 适配器)