适当的设计模式用于在两个不具有类似功能的类别之间进行选择(Appropriate design pattern for choosing between two classes which do no

编程入门 行业动态 更新时间:2024-10-15 18:30:15
适当的设计模式用于在两个不具有类似功能的类别之间进行选择(Appropriate design pattern for choosing between two classes which do not have similar functions)

我有两个类Workflow1.java和Workflow2.java。 在Selection.java类中,我希望能够将两个类中的一个实例化为静态成员,但是我无法实现工厂模式,因为Workflow1和Workflow2不能是子类,因为它们的方法不一样。 尽管他们通过完成不同的操作达到了同样的最终结果。 这种情况有设计模式吗?

例子:如果类是WalkHelper.java和DriveHelper.java,你需要的方法完全不同,但你试图达到的是相同的 - 到达目的地。 我没有创建walk()和drive()作为方法,因为WalkHelper.java已经存在于我们的代码库中,并且我正在向它添加DriveHelper.java。

I have 2 classes Workflow1.java and Workflow2.java. At a class Selection.java I want to be able to choose between instantiating one of the 2 classes as a static member however I cannot implement the factory pattern as Workflow1 and Workflow2 cannot be subclasses since their methods are not the same. Although they achieve the same end result they do so by doing entirely different operations. Is there a design pattern for this scenario?

Example: If the classes were WalkHelper.java and DriveHelper.java, the methods you need in each are entirely different but what you are trying to achieve is the same - reach a destination. I haven't created walk() and drive() as methods as WalkHelper.java has existed in our code base and I'm adding DriveHelper.java to it.

最满意答案

听起来你仍然可以使用Factory模式,但你可能不得不使用Adaptor使它们相等......不知道更多,这是一个非常难以回答的问题。

interface IFactory { void run(); String getResult(); } class Workflow1Adapter implements IFactory { Workflow1 wf1 = new Workflow1(); public void run() { wf1.doSomething(); } public String getResult() { wf1.doAnother(); } } class Workflow2Adapter implements IFactory { Workflow2 wf2 = new Workflow2(); public void run() { wf2.doThatThing(); } public String getResult() { wf2.doReturn(); } } class Workflow1 { public void doSomething() {} public String doAnother() {} } class Workflow2 { public void doThatThing() {} public String doReturn() {} }

It sounds like you can still use a Factory pattern but you may have to use an Adaptor to make them equal... Without knowing more, it's a pretty difficult question to answer.

interface IFactory { void run(); String getResult(); } class Workflow1Adapter implements IFactory { Workflow1 wf1 = new Workflow1(); public void run() { wf1.doSomething(); } public String getResult() { wf1.doAnother(); } } class Workflow2Adapter implements IFactory { Workflow2 wf2 = new Workflow2(); public void run() { wf2.doThatThing(); } public String getResult() { wf2.doReturn(); } } class Workflow1 { public void doSomething() {} public String doAnother() {} } class Workflow2 { public void doThatThing() {} public String doReturn() {} }

更多推荐

本文发布于:2023-08-04 20:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1422632.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类似   类别   两个   模式   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!