设计模式(装饰模式)
装饰模式用于给对象动态而灵活的添加属性,主要包含如下几个角色:
- Component:定义一个对象接口,可以给这些对象动态地添加职责,本例中是Product
- ConcreteComponent:具体的对象,用以被添加属性,本例中是ProductImpl,通过addAttribute被添加属性
- Decorator:装饰器的抽象,维持一个Component指针,并继承该指针;本例中是BaseChange
- ConcreteComponent:具体的装饰器,本例中是OneChange和TwoChange
代码如下:
- Product
public interface Product { public void addAttribute(); }
- ProductImpl
public class ProductImpl implements Product { @Override public void addAttribute() { System.out.println("Add base Attribute"); } }
- BaseChange
public class BaseChange implements Product { private Product product; public BaseChange(Product product){ this.product = product; } @Override public void addAttribute() { product.addAttribute(); } }
- OneChange && TwoChange
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"); } }
- App
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