Bridge Design Pattern

2018-03-22  本文已影响12人  zheting
package com.sheting.design.pattern.demo6;

/**
 * @Author SheTing
 * @Time 2018/3/22 8:56
 */
public interface Color {

    void applyColor();

}

package com.sheting.design.pattern.demo6;

/**
 * @Author SheTing
 * @Time 2018/3/22 8:59
 */
public class RedColor implements Color{

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

}

package com.sheting.design.pattern.demo6;

/**
 * @Author SheTing
 * @Time 2018/3/22 8:59
 */
public class GreenColor implements Color {

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

}

package com.sheting.design.pattern.demo6;

/**
 * @Author SheTing
 * @Time 2018/3/22 8:57
 */
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();

}

package com.sheting.design.pattern.demo6;

/**
 * @Author SheTing
 * @Time 2018/3/22 8:58
 */
public class Triangle extends Shape{

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

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

}

package com.sheting.design.pattern.demo6;

/**
 * @Author SheTing
 * @Time 2018/3/22 8:58
 */
public class Pentagon extends Shape{

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

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

}

package com.sheting.design.pattern.demo6;

/**
 * @Author SheTing
 * @Time 2018/3/22 9:00
 */
public class BridgePatternTest {

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

        Shape pent = new Pentagon(new GreenColor());
        pent.applyColor();
    }

}

上一篇 下一篇

猜你喜欢

热点阅读