设计模式-9-桥接模式

来源:互联网 发布:数据分析与知识发现 编辑:程序博客网 时间:2024/06/13 22:10

桥接模式:用于把抽象化与实现化解耦,使得二者可以独立变化

帮助理解:现有颜色(白,灰,黑)和形状(正方形,长方形,圆形),现需要将三种两两配对。



形状抽象类:

package com.structuralPattern.bridge.edition1;public abstract class Shape {    Color color;//颜色抽象类,是颜色和形状配对    public void setColor(Color color) {        this.color = color;    }        public abstract void draw();}

形状实际类:

package com.structuralPattern.bridge.edition1;public class Circle extends Shape{    public void draw() {        color.bepaint("圆形");    }}


package com.structuralPattern.bridge.edition1;public class Rectangle extends Shape{    public void draw() {        color.bepaint("长方形");    }}


package com.structuralPattern.bridge.edition1;public class Square extends Shape{    public void draw() {        color.bepaint("正方形");    }}

颜色抽象类:

package com.structuralPattern.bridge.edition1;public interface Color {    public void bepaint(String shape);}

实际颜色类

package com.structuralPattern.bridge.edition1;public class White implements Color{    public void bepaint(String shape) {        System.out.println("白色的" + shape);    }}

package com.structuralPattern.bridge.edition1;public class Gray implements Color{    public void bepaint(String shape) {        System.out.println("灰色的" + shape);    }}

package com.structuralPattern.bridge.edition1;public class Black implements Color{    public void bepaint(String shape) {        System.out.println("黑色的" + shape);    }}

将颜色和形状进行组合

package com.structuralPattern.bridge.edition1;/* * 将形状和颜色,进行组合 */public class Client {    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();    }}