设计模式之【装饰者--Decorator】

1、接口

1 package Decorator;
2 
3 public interface Sourceable {
4     public void method();
5 
6 }

2、接口实现类--被装饰者

 1 package Decorator;
 2 
 3 public class Source implements Sourceable{
 4 
 5     @Override
 6     public void method() {
 7         // TODO Auto-generated method stub
 8         System.out.println("接口原始方法的实现");
 9     }
10 
11 }

3、装饰类

 1 package Decorator;
 2 
 3 //装饰类,在原有类的基础上通过接口添加新方法
 4 public class Decorator implements Sourceable{
 5     private Sourceable source;
 6     
 7     public Decorator(Sourceable source){
 8         super();    //调用父类构造方法
 9         this.source = source;
10     }
11     
12     @Override
13     public void method() {
14         // TODO Auto-generated method stub
15         System.out.println("装饰前");
16         source.method();
17         System.out.println("装饰后");
18     }
19 
20 }

4、实现扩展

 1 package Decorator;
 2 
 3 public class DecoratorTest {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7         Sourceable    source = new Source();
 8         Sourceable    obj = new Decorator(source);
 9         obj.method();
10     }
11 
12 }

5、结果

装饰前
接口原始方法的实现
装饰后

装饰器模式的应用场景:

1、需要扩展一个类的功能。

2、动态的为一个对象增加功能,而且还能动态撤销。(继承不能做到这一点,继承的功能是静态的,不能动态增删。)

缺点:产生过多相似的对象,不易排错!

原文地址:https://www.cnblogs.com/pingzhanga/p/4674008.html