伪向后构建器模式?

发布于 2024-08-30 07:49:31 字数 560 浏览 6 评论 0原文

在遗留代码库中,我有一个非常大的类,其中包含太多的字段/职责。想象这是一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

幽梦紫曦~ 2024-09-06 07:49:31

适配器模式怎么样?

基本上是一个包装类,它具有您真正想要的所有功能,可以轻松地往返于 Pizza 类。

MenuPizza myPizza = new MenuPizza(pizza);
PizzaType pizzaType = myPizza.getPizzaType();
DoughType doughType = myPizza.getDoughType();

你可以提供相反的功能......

MenuPizza otherPizza = new MenuPizza(PizzaType.SUPREME, DoughType.SOUR);
Pizza pizzaPOJO = otherPizza.getPizzaPOJO();

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.

MenuPizza myPizza = new MenuPizza(pizza);
PizzaType pizzaType = myPizza.getPizzaType();
DoughType doughType = myPizza.getDoughType();

And you could provide the reverse functionality...

MenuPizza otherPizza = new MenuPizza(PizzaType.SUPREME, DoughType.SOUR);
Pizza pizzaPOJO = otherPizza.getPizzaPOJO();
清晰传感 2024-09-06 07:49:31

我认为这对于扩展函数来说是一个很好的用例,而 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文