little discussion on Strategy Pattern

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

little discussion on Strategy Pattern

Post 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.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post 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.
adiian
Forum Newbie
Posts: 2
Joined: Sat Sep 09, 2006 12:06 pm

Post 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
Post Reply