书城计算机大话设计模式
11030400000209

第209章 6 模式的简化

大B:“简化必须注意两点:1、一个装饰器类的接口必须与被装饰的类的接口相容。2、尽量保持Component作为一个‘轻’类。Component类的职责在于为各个具体装饰器类提供共同的接口,而不是存储数据,所以不要把太多的逻辑和状态放在Component类里面。省略Component接口,只有一个具体的ConcreteComponent类,则Decorater经常作为ConcreteComponent的子类。”

//Component。java 构件类

public abstract class Component

{

public abstract void doSomething();

}

//ConcreteComponent。java 具体构件类

public class ConcreteComponent extends Component

{

public void doSomething()

{

//provide implementation here

}

}

//Decorator。java 装饰器抽象类

public abstract class Decorator extends Component

{

protected Component component;

public Decorator(Component component)

{

this。component=component;

}

public void doSomething()

{

component。doSomething();

}

}

//ConcreteDecorator。java 具体装饰器类

public class ConcreteDecorator extends Decorator

{

public ConcreteDecorator(Component component)

{

super(component);

}

private void addedBehavior()

{

//some extra functionality goes here

}

public void doSomething()

{

component。doSomething();

addedBehavior();

}

}