Here is my initial code that I would like to modify by using strategy design pattern.

class Bar
{
  int a;
  int b;
  ...
}

Class Foo
{
  Bar *bar;

  bool action1(){ 
    // this function does a lot of work that only uses "bar.a"
  }
  bool action2(){ 
    // this function does also a lot of work that only uses "bar.a"
  }
  void command(){
    ...
    Bar bar2 = new Bar(); 
    bar = bar2; // this function modifies the attribute bar.
    ...
  }

  ...
}

I am trying to separate the code of both action1 and action2 from the class Foo by creating a strategy object that will implement those actions. I don't know which of those implementations is better.

First Solution:

class ActionStrategy {
  Bar *bar;

  bool action1();
  bool action2();
}

Class Foo
{
  Bar *bar;
  ActionStrategy strategy

  bool action1(){ 
    strategy.action1();
  }
  bool action2(){ 
    strategy.action2();
  }
  void command(){
    ...
    Bar bar2 = new Bar(); 
    bar = bar2; // this function modifies the attribute bar.
    ...
  }

  ...
}

Second Solution:

class ActionStrategy {
  int a;

  bool action1();
  bool action2();
}

Class Foo
{
  Bar *bar;
  ActionStrategy strategy

  bool action1(){ 
    strategy.action1();
  }
  bool action2(){ 
    strategy.action2();
  }
  void command(){
    ...
    Bar bar2 = new Bar(); 
    setBar(bar2); // this function modifies the attribute bar.
    ...
  }

  void setBar(Bar* target) {
    bar = target;
    strategy.a = target->a;
  }

  ...
}
有帮助吗?

解决方案

The answer may very be "neither." Neither of your solutions appear to cleanly separate out responsibility for the variable a and the two methods.

The answer you're looking for depends upon what a actually represents and what the methods are doing to it. Once you understand that, then you can follow the single responsibility principle and decide where to place the variable and methods.

At the moment, your solutions appear to be pushing too much knowledge regarding a and the methods that act upon a to classes that don't have responsibility for a. Perhaps the methods should be moved to Bar; have Foo instantiate Bar by passing a value of a; and have Foo call the methods off of Bar.

许可以下: CC-BY-SA归因
scroll top