装饰器模式

装饰器,两个角色,一个是待装饰者,一个是装饰者,就像我们早餐吃的煎饼,煎饼是待装饰者,其他的火腿、里脊、土豆丝、生菜等都是装饰者,但最终都没有改变这还是一个煎饼。

这里代码上有两个重要的点,一个是装饰者会也会继承或者实现被装饰者,第二是装饰者的构造函数会有一个类型为待装饰者的参数,代码示例如下:

 

package decorator;
public class DecoratorPattern {
    public static void main(String[] args) {
        Component p = new ConcreteComponent();
        p.operation();
        System.out.println("---------------------------------");
        Component d = new ConcreteDecorator(p);
        d.operation();
    }
}
//抽象构件角色
interface Component {
    public void operation();
}
//具体构件角色
class ConcreteComponent implements Component {
    public ConcreteComponent() {
        System.out.println("创建具体构件角色");
    }
    public void operation() {
        System.out.println("调用具体构件角色的方法operation()");
    }
}
//抽象装饰角色
class Decorator implements Component {
    private Component component;
    public Decorator(Component component) {
        this.component = component;
    }
    public void operation() {
        component.operation();
    }
}
//具体装饰角色
class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component);
    }
    public void operation() {
        super.operation();
        addedFunction();
    }
    public void addedFunction() {
        System.out.println("为具体构件角色增加额外的功能addedFunction()");
    }
}
posted @ 2023-12-13 14:17  求简君  阅读(24)  评论(0)    收藏  举报