第209章(1 / 1)

大话设计模式 吴强 500 字 2个月前

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

//Component.java构件类

publicabstractclassComponent

{

publicabstractvoiddoSomething();

}

//ConcreteComponent.java具体构件类

publicclassConcreteComponentextendsComponent

{

publicvoiddoSomething()

{

//provideimplementationhere

}

}

//Decorator.java装饰器抽象类

publicabstractclassDecoratorextendsComponent

{

protectedComponentponent;

publicDecorator(Componentponent)

{

this.orgponent=ponent;

}

publicvoiddoSomething()

{

ponent.doSomething();

}

}

//ConcreteDecorator.java具体装饰器类

publicclassConcreteDecoratorextendsDecorator

{

publicConcreteDecorator(Componentponent)

{

super(ponent);

}

privatevoidaddedBehavior()

{

//someextrafunctionalitygoeshere

}

publicvoiddoSomething()

{

ponent.doSomething();

addedBehavior();

}

}