When the context class can accept a null strategy, is there another way to do it without check if its null?
Is this considered a good strategy design implementation?
class MainApp{
static void Main(){
Context context = new Context();
while(true){
Strategy strategy = createConcreteStrategy(Console.ReadLine());
context.setStrategy(strategy);
context.run();
}
}
static void createConcreteStrategy(string input){
if( input == "strategyA" ){
return new StrategyA();
}
if( input == "strategyB" ){
return new StrategyB();
}
return null;
}
}
abstract class Strategy { public abstract void doSomething(); }
class Context{
Strategy strategy;
ClassX x;
public Context(){}
public void setStrategy(Strategy strategy){
this.strategy = strategy;
}
public void run(){
if( strategy != null ){
data = strategy.doSomething();
x.setData(data);
}
}
}
There is absolutely a way to avoid checking for null here! Use the null object pattern, i.e.
class NullStrategy: Strategy {
public void doSomething() {
}
}
and then the “default” case in createConcreteStrategy
is return new NullStrategy()
instead of return null
, and then you no longer have to check if strategy
is null in run
.
If you don’t want to call x.setData
with a null argument, then you could pass x
to the strategy. Here’s one possible implementation:
class NullStrategy: Strategy {
public void doSomething(ClassX x) {
// don't do anything with x
}
}
class RealStrategy: Strategy {
public void doSomething(ClassX x) {
var data = someOperation();
x.setData(data);
}
}
Pushing an if-statement into an instance of Strategy
makes sense to me in this situation.
3