23种设计模式学习之装饰者模式
装饰着模式是动态的增强类的功能,要求被装饰的类必选实现了某个接口
被装饰类接口
public interface Source { void method1(); }
被装饰类
public class SourceImpl implements Source { @Override public void method1() { System.out.println("2"); } }
装饰类
public class Decorator implements Source { private SourceImpl source; public Decorator(SourceImpl source) { super(); this.source = source; } @Override public void method1() { System.out.println(1); source.method1(); System.out.println(3); } }
实例
public class Demo { public static void main(String[] args) { Source source =new Decorator(new SourceImpl()); source.method1(); } }