Adding State in Decorator Pattern

后端 未结 3 881
眼角桃花
眼角桃花 2021-01-22 09:07

I wonder how to add state to the chain of decorators that will be available to the consumer. Given this simplified model:

abstract class AbstractPizza 
{
    pub         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-22 09:55

    The decorator pattern is for adding additional behavior to the decorated class without the client needing to adjust. Thus it is not intended for adding a new interface (e.g. hotness, cheese) to the thing being decorated.

    A somewhat bad example of what it might be used for is where you want to change how size is calculated: you could create a MetricSizePizzaDecorator that converts the size to/from English/metric units. The client would not know the pizza has been decorated - it just calls getSize() and does whatever it needs to do with the result (for example, to calculate the price).

    I would probably not use the decorator in my example, but the point is: it does not alter the interface. In fact, nearly all design patterns come down to that - adding variability to a design without changing interfaces.

提交回复
热议问题