jeudi 25 décembre 2014

PHP strategy pattern - interface vs inheritance?

I am stuck here at whether should I use interface or not. For instance,



interface ModelStrategy
{
public function respond();
}

interface Mammal
{
public function walk(Model $Model);
}

class Model implements ModelStrategy
{
public $text = null;

public function respond() {
return $this->text;
}
}

class CatModel extends Model implements ModelStrategy
{
public $text = 'Walk using four legs or whatever';

public function respond() {
return $this->text;
}
}

class Cat implements Mammal
{
public function walk(Model $Model)
{
return $Model->respond();
}
}


usage,



$mammal = new Cat;

function performWalk(Mammal $mammal){
$model = new CatModel();
return $mammal->walk($model);
}

$walk = performWalk($mammal);

var_dump($walk);


I can archive the same result above just with inheritance without interface, for instance,



class Model
{
public $text = null;

public function respond() {
return $this->text;
}
}

class CatModel extends Model
{
public $text = 'Walk using four legs or whatever';

public function respond() {
return $this->text;
}
}

class Mammal
{
public function walk(Model $Model)
{
return $Model->respond();
}
}

class Cat extends Mammal
{
public function walk(Model $Model)
{
return $Model->respond();
}
}


It seems to be a lot simpler with inheritance, what would you do and what do you suggest?


Aucun commentaire:

Enregistrer un commentaire