Strategy pattern á la „Head First Design Patterns“

<?php

/**
* Strategy design pattern example realized in PHP
*
* Inspired by „Head First Design Patterns
*
* @author <php@tschagrass.de>
*/
abstract class Animal {

protected $soundBehavior;
protected $moveBehavior;

public function performSound() {
$this->soundBehavior->performSound();
}
public function performMove() {
$this->moveBehavior->performMove();
}
public function setMoveBehavior($moveBehavior) {
if ($moveBehavior instanceof MoveBehavior) {
$this->moveBehavior = $moveBehavior;
}
}
}

// ——

interface SoundBehavior {
public function performSound();
}

interface MoveBehavior {
public function performMove();
}

// ——

class Barking implements SoundBehavior {
public function performSound() {
echo „I’m Barking \n“;
}
}

class Meowing implements SoundBehavior {
public function performSound() {
echo „I’m Meowing \n“;
}
}

class Doggystyling implements MoveBehavior {
public function performMove() {
echo „I’m Doggystyling \n“;
}
}

class Catwalking implements MoveBehavior {
public function performMove() {
echo „I’m Catwalking \n“;
}
}

class Jumping implements MoveBehavior {
public function performMove() {
echo „I’m Jumping \n“;
}
}

// ——

class Dog extends Animal {
public function __construct() {
$this->soundBehavior = new Barking();
$this->moveBehavior = new Doggystyling();
}
}

class Cat extends Animal {
public function __construct() {
$this->soundBehavior = new Meowing();
$this->moveBehavior = new Catwalking();
}
}

// ——

function makeAninimal() {
$i = rand(0, 1);
if ($i == 0) {
return new Dog;
}
return new Cat;
}

echo „<pre>“;
$animal = makeAninimal();
$animal->performSound();
$animal->performMove();
$animal->setMoveBehavior(new Jumping());
$animal->performMove();
echo „</pre>“;

Leave a Reply

You must be logged in to post a comment.