装饰器(Decorator)模式

public interface IDoThings {  
    public void doSomeThing();  
} 
public class DoThings implements IDoThings {
    @Override
    public void doSomeThing() {
        System.out.println("做一些事情");
    }
}
public class Decorator implements IDoThings {
    private IDoThings beverage;
    Decorator(IDoThings beverage){
        this.beverage =beverage;
    }
    @Override
    public void doSomeThing() {
        beverage.doSomeThing();
    }
}
public class Eat extends Decorator{
    Eat(IDoThings beverage){
        super(beverage);
    }
    @Override
    public void doSomeThing() {
        super.doSomeThing();
        System.out.println("吃饭");
    }
}
public class Run extends Decorator{
    Run(IDoThings beverage){
        super(beverage);
    }
    @Override
    public void doSomeThing() {
        super.doSomeThing();
        System.out.println("跑步");
    }
}
public class TestDecorator {
     public static void main(String[] args) {  
            IDoThings instance = new DoThings();  
            instance = new Eat(instance);  
            instance = new Run(instance);  
            instance.doSomeThing();
        }  
}

控制台输出为:

做一些事情
吃饭
跑步

代理模式和装饰器模式的区别

https://www.jianshu.com/p/c06a686dae39

原文地址:https://www.cnblogs.com/tonggc1668/p/7070506.html