简体   繁体   English

在策略模式中,处理共享行为的最佳方法是什么?

[英]In the strategy pattern, what's the best way to deal with shared behaviour?

I have implemented the strategy pattern - is there a smart way to deal with the duplication of function2() and function1() below? 我已经实现了策略模式-是否有一种聪明的方法来处理下面的function2()和function1()的重复?
The IBehaviour interface has other members that don't share functionality. IBehaviour接口具有其他不共享功能的成员。

class Behaviour1: IBehaviour
{
    public void DoSomething()
    {
        Function1();
    }
    //other functions of IBehaviour
}

class Behaviour2 : IBehaviour
{

   public void DoSomething()
   { 
       Function2();
       Function1();
   }
   //other functions of IBehaviour
}

class Behaviour3 : IBehaviour
{
    public void DoSomething()
    {
        Function2();
    }
    //other functions of IBehaviour
}

I already have one class to deal with this behaviour. 我已经有一堂课来处理这种行为。 Then I realised that different situations require different behaviours, so in this main class, I create a Behaviour object at run-time. 然后我意识到不同的情况需要不同的行为,因此在这个主类中,我在运行时创建了一个Behavior对象。 I am reluctant to create yet another class for Function1 and Function2, so I wondered if there is something that I am missing. 我不愿意为Function1和Function2创建另一个类,所以我想知道是否缺少某些东西。

One of two easy options comes to mind: 我想到了两个简单的选项之一:

  1. Make Behavior3 inherit from Behavior2 . 使Behavior3Behavior2继承。 I would only recommend this approach if you can establish a clear "IS A" relationship or this design approach could really give you problems later if things change with how Behavior2 works in relation to Behavior3 . 如果您可以建立明确的“ IS A”关系,或者如果Behavior2相对于Behavior3工作方式发生了变化,则此设计方法确实会在以后给您带来问题,我只会推荐这种方法。

  2. Move Function2() into a helper class that Behavior2 and Behavior3 can use indepedently. Function2()移到Behavior2Behavior3可以独立使用的帮助器类中。

If it's better reuse in compensation for a little more complexity that you want, separating IBehavior into IBehavior1 and IBehavior2 could be worthwhile. 如果更好地重用以补偿所需的更多复杂性, IBehavior分为IBehavior1IBehavior2可能是值得的。 Then Behavior1 would implement IBehavior1 , and Behavior3 would implement both, etc. This approach would go along the same line with single responsibilty and (maybe) interface segregation principles. 然后, Behavior1将实现IBehavior1 ,而Behavior3将实现这两​​者, IBehavior1 。此方法将遵循相同的原则,具有单一职责和(可能是)接口隔离原则。

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

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