当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 设计模式之桥接模式——Java语言描述

设计模式之桥接模式——Java语言描述

2019年01月11日  | 移动技术网IT编程  | 我要评论

桥接适用于把抽象化和实现化解耦,使得二者可以独立变化。这种类型的设计模式属于结构性模式,它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦

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

介绍

设计模式意图: 将抽象部分和实现部分分离,使得它们可以独立变化。

优点:

  1. 抽象和实现的分离
  2. 优秀的拓展能力

缺点: 桥接模式的引入会增加系统的理解和设计难度,由于聚合挂链关系建立在抽象层,要求开发者针对抽象设计与编程。

使用场景:

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

总结:
即我们可以通过使用接口类型的变量来调用实现类的引用。

实现

我们有一个作为桥接实现的 drawapi 接口和实现了 drawapi 接口的实体类 redcircle、greencircle。shape 是一个抽象类,将使用 drawapi 的对象。bridgepatterndemo,我们的演示类使用 shape 类来画出不同颜色的圆。

创建桥接接口

public interface drawapi {
   public void drawcircle(int radius, int x, int y);
}

创建实现了 drawapi 接口的实体桥接实现类

类redcircle

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

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 +"]");
   }
}

使用 drawapi 接口创建抽象类 shape

public abstract class shape {
   protected drawapi drawapi;
   protected shape(drawapi drawapi){
      this.drawapi = drawapi;
   }
   public abstract void draw();  
}

创建实现了 shape 接口的实体类。

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);
   }
}

使用 shape 和 drawapi 类画出不同颜色的圆

public class bridgepatterndemo {
   public static void main(string[] args) {
      shape redcircle = new circle(100,100, 10, new redcircle());
      shape greencircle = new circle(100,100, 10, new greencircle());
 
      redcircle.draw();
      greencircle.draw();
   }
}

输出结果

drawing circle[ color: red, radius: 10, x: 100, 100]
drawing circle[  color: green, radius: 10, x: 100, 100]

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网