Better Understand the 'Strategy' Design Pattern
Posted
by
Imran Omar Bukhsh
on Programmers
See other posts from Programmers
or by Imran Omar Bukhsh
Published on 2011-01-30T08:11:55Z
Indexed on
2011/01/30
15:32 UTC
Read the original article
Hit count: 615
Greetings
Hope you all are doing great. I have been interested in design patterns for a while and started reading 'Head First Design Patterns'. I started with the first pattern called the 'Strategy' pattern. I went through the problem outlined in the images below and first tried to propose a solution myself so I could really grasp the importance of the pattern. So my question is that why is my solution ( below ) to the problem outlined in the images below not good enough. What are the good / bad points of my solution vs the pattern? What makes the pattern clearly the only viable solution ? Thanks for you input, hope it will help me better understand the pattern.
MY SOLUTION
Parent Class: DUCK
<?php
class Duck
{
public $swimmable;
public $quackable;
public $flyable;
function display()
{
echo "A Duck Looks Like This<BR/>";
}
function quack()
{
if($this->quackable==1)
{
echo("Quack<BR/>");
}
}
function swim()
{
if($this->swimmable==1)
{
echo("Swim<BR/>");
}
}
function fly()
{
if($this->flyable==1)
{
echo("Fly<BR/>");
}
}
}
?>
INHERITING CLASS: MallardDuck
<?php
class MallardDuck extends Duck
{
function MallardDuck()
{
$this->quackable = 1;
$this->swimmable = 1;
}
function display()
{
echo "A Mallard Duck Looks Like This<BR/>";
}
}
?>
INHERITING CLASS: WoddenDecoyDuck
<?php
class WoddenDecoyDuck extends Duck
{
function woddendecoyduck()
{
$this->quackable = 0;
$this->swimmable = 0;
}
function display()
{
echo "A Wooden Decoy Duck Looks Like This<BR/>";
}
}
Thanking you for your input.
Imran
© Programmers or respective owner