装饰器模式

package decorator;

/**
 * @Author xxx
 * @Date 2021/6/17 14:20
 * @Email xxx
 * @Description: 装饰器模式
 * 4个角色
 *      基本的接口或者抽象类,提供方法
 *      具体的实现者
 *      装饰者
 *      具体的装饰者
 * 关系
 *      具体实现者实现基本接口,提供基本功能
 *      装饰者实现基本接口,并持有具体实现者的引用
 *      具体装饰者继承装饰者,并对重写装饰者的方法,实现具体功能的增强,实现构造方法
 */
interface Shape{
    void draw();
}
class RoundShape implements Shape{

    @Override
    public void draw() {
        System.out.println("画圆形");
    }
}
class SquareShape implements Shape{

    @Override
    public void draw() {
        System.out.println("画正方形");
    }
}
abstract class ShapeDecorator implements Shape{
    private Shape decoratorShape;
    public ShapeDecorator(Shape decoratorShape) {
        this.decoratorShape = decoratorShape;
    }

    public void draw() {
        decoratorShape.draw();
    }
}
class RedDecoratorShape extends ShapeDecorator{

    public RedDecoratorShape(Shape decoratorShape) {
        super(decoratorShape);
    }

    @Override
    public void draw() {
        setRedColor();
    }

    private void setRedColor() {
        super.draw();
        System.out.println("画红色的");
    }

}
public class DecoratorPatternDemo {
    public static void main(String[] args) {
        RoundShape roundShape = new RoundShape();
        SquareShape squareShape = new SquareShape();
        new RedDecoratorShape(roundShape).draw();
        new RedDecoratorShape(squareShape).draw();
    }
}

上一篇:springboot优雅实现工厂模式,策略模式——利用spring自动注入list,map性质


下一篇:【Swift Mac开发】修改NSTableView的headerView的背景颜色