简体   繁体   English

装饰器图案装饰器限制

[英]decorator pattern decorator limit

I am currently writing a program using the decorator pattern. 我目前正在使用装饰器模式编写程序。 I am trying to find out how to limit the amount of decorators I can add to the first class. 我试图找出如何限制可以添加到第一堂课的装饰器的数量。 Such as: 如:

Pizza plainPizza = new PlainPizza;
Pizza sausage = new Sausage(plainPizza);

How could I code this where I can be limited to the amount of decorators I add on. 我该如何编写代码,以限制我添加的装饰器数量。 Such as if I try to add this on top of the previous code: 例如,如果我尝试将其添加到之前的代码之上:

Pizza pepperoni = new Pepperoni(sausage);

How can I prevent it from allowing pepperoni to be added/wrapped? 如何防止它允许添加/包裹意大利辣香肠?

I am attempting to use a throw exception, but the problem is, my decorators call its superclass, so I can't test before initializing the instance variable! 我正在尝试使用throw异常,但是问题是,我的装饰器调用了它的超类,因此在初始化实例变量之前我无法进行测试!

You can use a Builder pattern to create a builder that will apply all types of decorators that you need. 您可以使用“ 构建器”模式来创建一个构建器,该构建器将应用所需的所有类型的装饰器。 Builder could also internally keep track of how many decorators you applied and react accordingly if attempt to add more than it's allowed is made. Builder也可以在内部跟踪您应用了多少个装饰器,如果尝试添加超出允许的数量,则做出相应的反应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM