伪向后构建器模式?
在遗留代码库中,我有一个非常大的类,其中包含太多的字段/职责。想象这是一个 Pizza 对象。
它具有高度精细的字段,例如:
- hasPepperoni
- hasSausage
- hasBellPeppers
我知道当这三个字段为真时,我们就有了 Supreme 披萨。但是,此类不开放扩展或更改,因此我无法添加 PizzaType 或 isSupreme() 等。整个代码库中的人们都会重复相同的 if(a && b && c) 然后 isSupreme)
逻辑遍布各处。这个问题涉及相当多的概念,所以我正在寻找一种方法来将该对象解构为许多子对象,例如伪向后构建器模式。
PizzaType pizzaType = PizzaUnbuilder.buildPizzaType(Pizza); //PizzaType.SUPREME
Dough dough = PizzaUnbuilder.buildDough(Pizza);
这是正确的方法吗?这种模式已经存在吗?
In a legacy codebase I have a very large class with far too many fields/responsibilities. Imagine this is a Pizza object.
It has highly granular fields like:
- hasPepperoni
- hasSausage
- hasBellPeppers
I know that when these three fields are true, we have a Supreme pizza. However, this class is not open for extension or change, so I can't add a PizzaType, or isSupreme(), etc. Folks throughout the codebase duplicate the same if(a && b && c) then isSupreme)
logic all over place. This issue comes up for quite a few concepts, so I'm looking for a way to deconstruct this object into many subobjects, e.g. a pseudo-backwards Builder Pattern.
PizzaType pizzaType = PizzaUnbuilder.buildPizzaType(Pizza); //PizzaType.SUPREME
Dough dough = PizzaUnbuilder.buildDough(Pizza);
Is this the right approach? Does this pattern exist already?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
适配器模式怎么样?
基本上是一个包装类,它具有您真正想要的所有功能,可以轻松地往返于 Pizza 类。
你可以提供相反的功能......
How about the Adapter Pattern?
Basically a wrapper class that has all the functionality you really want which can go easily back and forth to a Pizza class.
And you could provide the reverse functionality...
我认为这对于扩展函数来说是一个很好的用例,而 java 中不存在扩展函数。相反,我认为最简单的解决方案是创建一个类并将扩展的方法添加到该实用程序类中作为静态方法;
PizzaUtils.isSupreme(披萨披萨)
。I think this would be a great use case for extension functions, which don't exist in java. In lieu of that the simplest solution in my mind is to create a class and add the methods that would be extensions into that utility class as static methods;
PizzaUtils.isSupreme(Pizza pizza)
.