Adapter-适配器设计模式

Adapter-适配器设计模式

1、类图展示

这里写图片描述

2、编码步骤

1、编写Shape抽象类

/**
 * 定义抽象图形类
 * @author SoftStar
 */
abstract class Shape {
    private int x, y;
    public Shape() {
    }
    public Shape(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public void setLocation(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public int[] getLocation() {
        return new int[] { x, y };
    }
    abstract void display();
}

2、编写Point、Line、Sequare实体类

//Point类
public class Point extends Shape {
    int x, y;

    public Point() {
    }
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    @Override
    void display() {
        System.out.println("A point [" + x + "," + y + "]");
    }
}
//Line类
public class Line extends Shape {
    int x, y;
    public Line() {
    }
    public Line(int x, int y) {
        this.x = x;
        this.y = y;
    }
    @Override
    void display() {
        System.out.println("A Line [" + x + "," + y + "]");
    }
}
//Sequare
public class Sequare extends Shape {
    int x, y;
    public Sequare() {
    }
    public Sequare(int x, int y) {
        this.x = x;
        this.y = y;
    }
    @Override
    void display() {
        System.out.println("A Sequare [" + x + "," + y + "]");
    }
}

3、当想引用一个已存在的类的方法

//NewCircle实体类 [已存在]
public class NewCircle {
    private int x, y;
    public NewCircle() {
    }
    public NewCircle(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public void setLocation() {
        this.x = x;
        this.y = y;
    }
    public int[] getLocation() {
        return new int[] { x, y };
    }
    public void display() {
        System.out.println("A NewCircle [" + x + "," + y + "]");
    }
    public void OtherMethod() {
        System.out.println("Other Method");
    }
}

4、创建适配器类

//Cicle适配器类
public class Circle extends Shape {
    private NewCircle circle;
    public Circle() {
        circle = new NewCircle();
    }
    public Circle(int x, int y) {
        circle = new NewCircle(x, y);
    }
    @Override
    void display() {
        circle.display();
    }
}

5、测试类

//测试类
public class Main {
    public static void main(String[] args) {
        Shape shape = new Line(10, 10);
        shape.display();
        Shape shape2 = new Circle(5, 5);
        shape2.display();
    }
}

6、输出显示

A Line [10,10]
A NewCircle [5,5]

3、Adapter模式特征

意图: 是控制范围之外的一个原有对象与某个接口匹配。

解决方案: Adapter模式提供了具有所需接口的包装类。

参与者与协作者:
Adapter改变了Adapter的接口,是Adapter与Adapter的基类Target匹配。这样Client就可以使用Adapter了,好像他是Target类型。

实现: 将原有类包含在另一个类之中。让包含类与需要的接口匹配,调用被包容的类的方法。
这里写图片描述

Adapter模式的通用结构图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值