设计模式(8)--桥接模式

什么是桥接模式?
桥接模式是一种结构型模式,用于把抽象和实现分离。它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦。

为什么使用桥接模式?
种模式涉及到一个作为桥接的接口,使得实体类的功能独立于接口实现类。这两种类型的类可被结构化改变而互不影响。

桥接模式的使用场景?
1、如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系。
2、对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用。

如何实现?
我们先看一个简单的接口和两个实现:

public interface DrawAPI {
    public void drawCircle(int radius, int x, int y);
}
public class GreenCircle implements DrawAPI{

    public void drawCircle(int radius, int x, int y) {
        System.out.println("Drawing Circle[ color: green, radius: "
                + radius +", x: " +x+", "+ y +"]");
    }
}
public class RedCircle implements DrawAPI{
    public void drawCircle(int radius, int x, int y) {
        System.out.println("Drawing Circle[ color: red, radius: "
                + radius +", x: " +x+", "+ y +"]");
    }
}

一个画圆的接口和两个不同颜色的实现类。

桥接类:

public abstract class Shape {
    protected DrawAPI api;
    protected Shape(DrawAPI api){
        this.api = api;
    }

    public abstract void draw();
}
public class Circle extends Shape{
    private  int x, y, redius;
    private DrawAPI api;

    public Circle(int x,int y,int redius,DrawAPI api){
        super(api);
        this.x = x;
        this.y = y;
        this.redius = redius;
    }
    public void draw() {
        api.drawCircle(redius,x,y);
    }
}

调用客户端:

public class Client {
    public static void main(String[] args) {
        Shape shape1 = new Circle(100,100, 10, new RedCircle());
        Shape shape2 = new Circle(100,100, 10, new GreenCircle());

        shape1.draw();
        shape2.draw();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

专注网赚的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值