设计模式之装饰模式(六)
装饰模式是动态的扩展一个对象的功能,而不需要改变原始类代码的一种成熟模式。在装饰模式中,具体组件类和具体装饰类是该模式中的最重要的两个角色。
1。抽象组件类
public abstract class Car {abstract void operation();}public class BenQ extends Car{void operation(){System.out.println("I'm "+this.getClass().getName());}}public class Decorator extends Car {private Car car; public Decorator(Car car) { this.car = car; } public void operation() { car.operation(); } }public class BeforeDecorator extends Decorator {public BeforeDecorator(Car car) { super(car); } public void operation() { before(); super.operation(); } private void before() { System.out.println("before: I'm "+this.getClass().getName()); } }public class AfterDecorator extends Decorator {public AfterDecorator(Car car) { super(car); } public void operation() { super.operation(); after(); } private void after() { System.out.println("after: I'm "+this.getClass().getName()); } }public class Test {public static void main(String[] args) {Car car = new BenQ(); car.operation(); car = new BeforeDecorator(new BenQ()); car.operation(); car = new AfterDecorator(new BenQ()); car.operation(); car = new AfterDecorator(new BeforeDecorator(new BenQ())); car.operation(); car = new BeforeDecorator(new AfterDecorator(new BenQ())); car.operation(); }}