07 桥接模式(Bridge Design Pattern)

一句话概括:把Color抽象出来并作为Shape的一个属性,在Shape初始化的时候确定它是值。

将抽象部分与它的实现部分分离,使他们都可以独立变化。

桥接模式将继承关系转化成关联关系,它降低了类与类之间的耦合度,减少了系统中类的数量,也减少了代码量。

public interface Color{
    void applyColor();
}
public abstract class Shape{

    //桥接
    //Composition - implementor
    protected Color color;

    //constructor with implementor as input argument
    public Shape(Color c){
        this.color = c;
    }

    abstract public void applyColor();
}

The implementation of Shape

public class Triangle extends Shape{
    public Triangle(Color c){
        super(c);
    }

    @Override
    public void applyColor(){
        System.out.print("Triangle filled with color ");
        this.color.applyColor();
    }
}
public class Pentagon extends Shape{

    public Pentagon(Color c) {
        super(c);
    }

    @Override
    public void applyColor() {
        System.out.print("Pentagon filled with color ");
        color.applyColor();
    }

}

The implementation of Color

public class RedColor implements Color{

    public void applyColor(){
        System.out.println("red");
    }
}

public class GreenColor implements Color{
    public void applyColor(){
        System.out.println("green");
    }
}

Lets test our bridge pattern implementation with a test program

public class BridgePatternTest{
    public static void main(String[] args){
        Shape tri = new Triangle(new RedColor());
        tri.applyColor();

        Shape pent = new Pentagon(new GreenClor());
        tri.applyColor();
    }
}

The output of above bridge pattern test progran.

Triangle filled with color red.
Pentagon filled with color green.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,499评论 0 10
  • 目前我所接触过的所有编程语言都只有掌握三个内容就可以了:就是输入、处理、输出。我们已经安装好了Python,可以来...
    孙亖阅读 1,346评论 0 1
  • 在我心里,金庸的江湖,从来都不是初生牛犊不怕虎的热血青年,而是热血未尽壮心犹在的一代英豪,拥有着其独特的恢宏悲壮的...
    蕴_Caroline阅读 1,096评论 9 9
  • 文字/摄影:若木菡 水墨染山青,丹颜绣画屏。 千山腾细浪,万壑见云扃。 猿啸何知处,莺啼玉树亭。 香风平地起,花雨...
    若木菡阅读 996评论 30 35