装饰模式用于给对象动态而灵活的添加属性,主要包含如下几个角色:
代码如下:
public interface Product { public void addAttribute(); }
public class ProductImpl implements Product { @Override public void addAttribute() { System.out.println("Add base Attribute"); } }
public class BaseChange implements Product { private Product product; public BaseChange(Product product){ this.product = product; } @Override public void addAttribute() { product.addAttribute(); } }
public class OneChange extends BaseChange { public OneChange(Product product) { super(product); } @Override public void addAttribute() { super.addAttribute(); System.out.println("One Change"); } }
public class TwoChange extends BaseChange { public TwoChange(Product product) { super(product); } @Override public void addAttribute() { super.addAttribute(); System.out.println("Two Change"); } }
public class App { public static void main(String[] args) { Product product = new ProductImpl(); Product change = new TwoChange(new OneChange(product)); change.addAttribute(); } }
输出结果为:
Add base Attribute
One Change
Two Change
原文:http://www.cnblogs.com/Fredric-2013/p/4572218.html