美文网首页
Bridge Design Pattern

Bridge Design Pattern

作者: zheting | 来源:发表于2018-03-22 09:08 被阅读12次
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();
    }

}

相关文章

网友评论

      本文标题:Bridge Design Pattern

      本文链接:https://www.haomeiwen.com/subject/itmoqftx.html