装饰器模式的应用场景:1、需要扩展一个类的功能。2、动态的为一个对象增加功能,而且还能动态撤销。(继承不能做到这一点,继承的功能是静态的,不能动态增删。) 源接口:
1 public interface Sourceable { 2 3 void method(); 4 }
Source类:
1 public class Source implements Sourceable { 2 @Override 3 public void method() { 4 System.out.println("source.method()..."); 5 } 6 }
装饰器类:
1 public class Decorator implements Sourceable { 2 3 private Sourceable source; 4 public Decorator(Sourceable source) { 5 this.source = source; 6 } 7 8 @Override 9 public void method() { 10 System.out.println("Decorator decorate 1"); 11 source.method(); 12 System.out.println("Decorator decorate 2"); 13 } 14 15 public static void main(String[] args) { 16 Sourceable source = new Source(); 17 Sourceable sourceable = new Decorator(source); 18 sourceable.method(); 19 } 20 }
时间: 2024-12-17 17:11:59