Question

I have implemented the strategy pattern - is there a smart way to deal with the duplication of function2() and function1() below?
The IBehaviour interface has other members that don't share functionality.

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. I am reluctant to create yet another class for Function1 and Function2, so I wondered if there is something that I am missing.

Was it helpful?

Solution

One of two easy options comes to mind:

  1. Make Behavior3 inherit from Behavior2. 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.

  2. Move Function2() into a helper class that Behavior2 and Behavior3 can use indepedently.

OTHER TIPS

If it's better reuse in compensation for a little more complexity that you want, separating IBehavior into IBehavior1 and IBehavior2 could be worthwhile. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top