设计模式-桥接模式

1、概述

结构型模式

桥接模式是软件设计模式中最复杂的模式之一,它把事物对象和其具体行为、具体特征分离开来,使它们可以各自独立的变化。

桥接(Bridge)模式包含以下主要角色:

抽象化(Abstraction)角色 :定义抽象类,并包含一个对实现化对象的引用。
扩展抽象化(Refined Abstraction)角色 :是抽象化角色的子类,实现父类中的业务方法,并通过组合关系调用实现化角色中的业务方法。
实现化(Implementor)角色 :定义实现化角色的接口,供扩展抽象化角色调用。
具体实现化(Concrete Implementor)角色 :给出实现化角色接口的具体实现。

2、优缺点

优点
1、分离抽象接口及其实现部分。提高了比继承更好的解决方案。
2、桥接模式提高了系统的可扩充性,在两个变化维度中任意扩展一个维度,都不需要修改原有系统。
3、实现细节对客户透明,可以对用户隐藏实现细节。

缺点
1、桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。
2、桥接模式要求正确识别出系统中两个独立变化的维度,因此其使用范围具有一定的局限性。

3、实现方式


//测试类
public class Test {

    public static void main(String[] args) {
        //白色
        Color white = new White();
        //正方形
        Shape square = new Square();
        //白色的正方形
        square.setColor(white);
        square.draw();
        
        //长方形
        Shape rectange = new Rectangle();
        rectange.setColor(white);
        rectange.draw();


        //灰色
        Color gray = new Gray();
        //圆形
        Shape circle = new Circle();
        circle.setColor(gray);
        circle.draw();
    }

}


public abstract class Shape {
    Color color;

    public void setColor(Color color) {
        this.color = color;
    }
    
    public abstract void draw();
}


public class Circle extends Shape{

    public void draw() {
        color.bepaint("圆形");
    }
}


public class Rectangle extends Shape{

    public void draw() {
        color.bepaint("长方形");
    }

}


public class Square extends Shape{

    public void draw() {
        color.bepaint("正方形");
    }

}


public interface Color {
    public void bepaint(String shape);
}


public class White implements Color{

    public void bepaint(String shape) {
        System.out.println("白色的" + shape);
    }

}


public class Gray implements Color{

    public void bepaint(String shape) {
        System.out.println("灰色的" + shape);
    }
}


public class Black implements Color{

    public void bepaint(String shape) {
        System.out.println("黑色的" + shape);
    }
}

4、应用场景

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

This entry was posted in 应用, 设计模式. Bookmark the permalink.

发表评论