Design Pattern Explained 读书笔记四——Adapter

What?

Convert the interface of a class into another interface
that the clients expect. Adapter lets classes work together
that could not otherwise because of incompatible inter-
faces. ——GOF
先来个例子:
比如我接到需求要开发一套图形系统,于是我设计
统一接口(为了多态性)Shape,
Shape接口的行为是: display()

其中有一些实现类如,Squares等等

package com.adapter;
public interface Shape {

    void display();

    // ....

}
package com.adapter;
public class Squares implements Shape {

    @Override
    public void display() {
        System.out.println("Squares");
    }
    // ....
}

当我在设计圆这一实现的时候,发现小王已经写过了这个实现,并且逻辑完全一致,那聪明的我当然要复用了。但是,他的接口、方法参数各种不一致,难道我要改动?!怎么用?于是我想使用Adapter,来复用小王的实现,同时满足我的代码设计结构,让客户端依旧使用Shape接口。

package com.adapter;

import com.adaptee.SpecialCircle;
import com.adaptee.SpecialShape;

/** * this is Adapter * */
public class Circle implements Shape {

    /* * this is Adaptee */
    SpecialShape speicalCircle = new SpecialCircle();

    @Override
    public void display() {
        speicalCircle.displaySpecial();
    }
}
package com.adapter;

public class Client {

    public static void main(String[] args) {

        Shape shape = new Circle();

        /** * client完全不用管底层到底是怎么回事,依旧通过Shape去统一处理 */
        shape.display();

    }

}

UML图:
Design Pattern Explained 读书笔记四——Adapter_第1张图片

这是两种典型adapter设计模式的一种:对象Adapter。
适配对象:(Shape)Circle;
被适配对象:(SpecialShape)SpecialCircle

The Adapter Pattern: Key Features

Intent : Match an existing object beyond your control to a particular interface.

Problem : A system has the right data and behavior but the wrong interface. Typically used when you have to make something a derivative of an abstract class we are defining or already have.

Solution : The Adapter provides a wrapper with the desired interface.
Participants and Collaborators
The Adapter adapts the interface of an Adaptee to match that of the Adapter’s Target (the class it derives from). This allows the Client to use the Adaptee as if it were a type of Target.

Consequences : The Adapter pattern allows for preexisting objects to fit into new class structures without being limited by their interfaces.

Implementation : Contain the existing class in another class. Have the containing class match the required interface and call the methods of the contained class.

两种adapter的典型UML图:

有了adapter设计模式,不必去担心现有代码中类的接口问题了。如果需要使用一个类就可以用adapter的设计模式去给这个类包装出一个正确的接口。

Adapter与Facade的比较:

相同:都是将老的系统包装起来。都是在新接口中复用老的系统代码。
不同:Adapter要做的是将一个错误的已经存在的接口转化为目前新的接口,我调新的接口也同样做老的事情(而且代码复用)。Facade纯粹是通过组合单纯的整合、复用老的系统代码。
Design Pattern Explained 读书笔记四——Adapter_第2张图片
总之:
Facade简化系统,而Adapter是一个已有接口转化为另一个新接口。

How

见代码实例。也就是说,你想用Shape接口去做SpecialShape的事情——SpecialCircle。但是你无法直接使用SpecialShape.SpecialCircle,因为你的设计是Shape接口。所以你用Adapter模式解决问题。

你可能感兴趣的:(java,设计模式,Pattern,Adapter,适配器)