本文章,摘抄自:2018黑马程序最新面试题汇总
顾名思义,装饰模式就是给一个对象增加一些新的功能,而且是动态的,要求装饰对象和被装饰对象实现同一个接口,装饰对象持有被装饰对象的实例。
1 public interface ISourceable { 2 3 public void method(); 4 }
1 public class Source implements ISourceable { 2 3 @Override 4 public void method() { 5 System.out.println("the original method"); 6 } 7 8 }
1 public class Decorator implements ISourceable { 2 3 private ISourceable source; 4 5 public Decorator(ISourceable source) { 6 super(); 7 this.source = source; 8 } 9 10 @Override 11 public void method() { 12 System.out.println("before decorator"); 13 source.method(); 14 System.out.println("after decorator"); 15 } 16 17 }
测试方法:
1 @Test 2 public void test() { 3 ISourceable sourceable = new Source(); 4 ISourceable obj = new Decorator(sourceable); 5 obj.method(); 6 }