设计模式之装饰模式(六)
装饰模式是动态的扩展一个对象的功能,而不需要改变原始类代码的一种成熟模式。在装饰模式中,具体组件类和具体装饰类是该模式中的最重要的两个角色。
1。抽象组件类
public abstract class Car {abstract void operation();}2。具体组件类
public class BenQ extends Car{void operation(){System.out.println("I'm "+this.getClass().getName());}}3。装饰类
public class Decorator extends Car {private Car car; public Decorator(Car car) { this.car = car; } public void operation() { car.operation(); } }4。具体装饰类
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()); } }5。测试类
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(); }}装饰模式的优点:
1。被装饰者和装饰者是松耦合关系,由于装饰仅仅依赖于抽象组件,因此具体装饰只知道它要装饰的对象是抽象组件的某一个子类的实例,但不需要知道是哪一个具体子类。
2。装饰模式满足‘开-闭原则’OCP,不必修改具体组件,就可以增加新的针对该具体组件的具体装饰。
3。可以使用多个具体装饰来装饰具体组件的实例。