Page 1 of 1

little discussion on Strategy Pattern

Posted: Fri Dec 22, 2006 6:11 am
by jmut
Ok I am trying to implement Strategy Pattern but it is not exactly following the books :)

I will describe the problem I have in terms of this UML diagram
http://www.exciton.cs.rice.edu/JavaReso ... attern.htm

Picture is all very clear.
You can add more Contexts and you still can use ConcreteStrategies.
But what happen if the ConcreteStrategy somehow depends on the Context.
How will you tackle this sittuation.

worst case you will have something like this in the Strategie:

Code: Select all

function AlgorithmInterface($context)
{
     switch (get_class($context)) {
            case 'context1';
              //do something specific for context 1.
            case 'context2';
              //do something specific for context 1.
     }
}
Meaning that AlgorithmInterface() is not actually using the context only for input info.....but doing tottaly different stuff based on context (here strategy pattern is spoiled)

I am pretty sure strategy should not be used if this is the case...but not sure.

Would be glad to hear you comment on this one.

Posted: Fri Dec 22, 2006 7:49 am
by Weirdan
I would go with some mix of strategy and visitor in this case:

Code: Select all

class AlgorithmInterface {
    public function process($context)
    {
         $context->doSpecificContextThing($this);
    }
    public function doSomething($context) {
         //.....
    }
    public function doSomethingElse($context) {
         // .......
    }
}

class Context1 {
    public function doSpecificContextThing($strategy) {
       $strategy->doSomething($this);
       $strategy->doSomethingElse($this); 
   }
}

class Context2 {
    public function doSpecificContextThing($strategy) {
         $strategy->doSomethingElse($this);        
         $strategy->doSomething($this);
    }
}
Here concrete context defines the order in which strategy methods would get executed.

Posted: Sun Feb 11, 2007 12:43 pm
by adiian
What you have written is actually the template method pattern. They are intended to do a similar job, but are totally different. See Template Method Pattern and Strategy Pattern on http://www.oodesign.com