桥接模式(七)

是用于把抽象化与实现化解耦,使得二者可以独立变化
涉及到一个作为桥接的接口,使得实体类的功能独立于接口实现类。这两种类型的类可被结构化改变而互不影响

菜鸟案例:
我们有一个作为桥接实现的 DrawAPI 接口和实现了 DrawAPI 接口的实体类 RedCircle、GreenCircle。Shape 是一个抽象类,将使用 DrawAPI 的对象。BridgePatternDemo,我们的演示类使用 Shape 类来画出不同颜色的圆
在这里插入图片描述

把图例拆看

在这里插入图片描述
这就是很正常的一个接口,两个实现类。
再看下面的图
在这里插入图片描述
先不讨论Shape是什么类,看Shape就知道Shape里有一个属性,属性是DrawAPI,方法有两个,一个是Shape(),一个是draw() ,再看它的子类,有一个draw(),肯定就是父类的,那根据Shape的类型可以决定子类是实现还是覆盖,再想一下,Shapedraw的能力吗?只是图形,不知道是圆还是正方形等怎么画,所以Shape抽象类draw() 是抽象方法,子类是实现的父类的draw() 方法

再看下面的
在这里插入图片描述
画一个图形先要知道它是什么图形吧,所以关联Shape ,它的子类决定画什么形状(图上没有,看上上张图),颜色就用DrawAPI的实现类就行,因为Shape里有它的接口,就可以new RedCircle或者GreenCircle作为参数传进Shape 类里转型成DrawAPI,这样Shape类里就可以组装成一个完整的图案

上程序

(1)创建桥接实现接口。

DrawAPI.java

public interface DrawAPI {
   public void drawCircle(int radius, int x, int y);
}
(2)创建实现了 DrawAPI 接口的实体桥接实现类。

RedCircle.java

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

GreenCircle.java

public class GreenCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: green, radius: "
         + radius +", x: " +x+", "+ y +"]");
   }
}
(3)使用 DrawAPI 接口创建抽象类 Shape。

Shape.java

public abstract class Shape {
   protected DrawAPI drawAPI;
   protected Shape(DrawAPI drawAPI){
      this.drawAPI = drawAPI;
   }
   public abstract void draw();  
}

和上面分析的一样,这个类就是这么写的,当然protected 如果根据图的话应该是public,这个影响不大,可以不用管。

(4)创建实现了 Shape 接口的实体类。

Circle.java

public class Circle extends Shape {
   private int x, y, radius;
 
   public Circle(int x, int y, int radius, DrawAPI drawAPI) {
      super(drawAPI);
      this.x = x;  
      this.y = y;  
      this.radius = radius;
   }
 
   public void draw() {
      drawAPI.drawCircle(radius,x,y);
   }
}
(5)使用 Shape 和 DrawAPI 类画出不同颜色的圆。

BridgePatternDemo.java

public class BridgePatternDemo {
   public static void main(String[] args) {
   //这最后一个参数直接new的RedCircle或者GreenCircle,这是实体类,
   //而再往下走就是RedCircle转成它的接口DrawAPI ,但是它的这个接口已经有了它实体类的方法体了
      Shape redCircle = new Circle(100,100, 10, new RedCircle());
      Shape greenCircle = new Circle(100,100, 10, new GreenCircle());
 
      redCircle.draw();
      greenCircle.draw();
   }
}
(6)执行程序,输出结果:
Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[  color: green, radius: 10, x: 100, 100]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值