常用设计模式-桥接模式(Bridge Pattern)
一、桥接模式目的
在此模式中,使用一个案例去演示为什么要使用桥接模式。假如有一个场景,有两种形状图形,Circle 和 Rectangle 图形,分别需要实现红蓝两种颜色的四个图形,假如采用继承的方法,方法一,如下:
abstract class Shape {
abstract void draw();
}
class RedCircle extends Shape {
@Override
public void draw() {
System.out.println("draw Red Color");
}
}
class BlueCircle extends Shape {
@Override
public void draw() {
System.out.println("draw Blue Color");
}
}
class RedRectangle extends Shape {
@Override
public void draw() {
System.out.println("draw Red Color");
}
}
class BlueRectangle extends Shape {
@Override
public void draw() {
System.out.println("draw Blue Color");
}
}
public class Main{
public static void main(String args[]){
new RedCircle().draw();
new BlueCircle().draw();
}
}
//结果
draw Red Color
draw Blue Color
可见假如有 N 种图形和 M 种颜色,就需要 N*M个子类继承 Shape 抽象类,并且耦合度很高,拓展不灵活。这明显不是一种好的设计模式。因此有一种桥接模式的结构型设计模式,可以将【抽象部分】与【实现部分】分离,降低耦合度的同时,只需要 N + M 个类。
从以上方法一,抽象部分即为 abstract class Shape 抽象类,实现部分即为 RedCircle BlueCircle RedRectangle BlueRectangle 四个实现类,可见 Shape 图形类和 颜色的实现耦合在了一起,为此可以使用方法二,也即桥接模式去讲它们分离。如下:
interface Color {
public void draw();
}
class Red implements Color{
@Override
public void draw() {
System.out.println("draw Red");
}
}
class Blue implements Color{
@Override
public void draw() {
System.out.println("draw Blue");
}
}
abstract class Shape {
protected Color color;
public Shape(Color color) {
this.color = color;
}
abstract void draw();
}
class Circle extends Shape{
public Circle(Color color) {
super(color);
}
@Override
void draw() {
color.draw();
}
}
class Rectangle extends Shape{
public Rectangle(Color color) {
super(color);
}
@Override
void draw() {
color.draw();
}
}
public class Demo {
public static void main(String[] args) {
Shape shape1 = new Circle(new Blue());
shape1.draw();
Shape shape2 = new Rectangle(new Red());
shape2.draw();
}
}
//结果
draw Blue
draw Red
使用桥接模式可以将图形和颜色两个维度分离,两个维度都可以独立进行变化和扩展,如果要新增其他颜色,只需添加新的 Color
子类,不影响图形类;反之亦然。
二、实现思路
-
创建一个抽象类,拥有一个引用变量,维护其他类的实现。在构造方法中便可传入该引用。即以下的图形抽象类。
abstract class Shape { protected Color color; public Shape(Color color) { this.color = color; } abstract void draw(); }
-
创建各种图形继承类,继承这个抽象类。如 Circle 、Rectangle类,在此类中,可以对抽象类进行扩展,子类实现其父类的抽象方法时可以对抽象方法进行各种变化或定制。
-
创建 Color 接口,提供第一步抽象类中实例引用的各种方法-具体实现,是一种接口标准。
-
创建 Color 接口的具体实现,对接口的具体实现进行重写,提供具体的操作。