I´m trying to understand the strategy pattern in PHP. My Example is based on this tutorials: http://www.d-mueller.de/blog/5-php-patterns-im-schnelldurchlauf-factory-iterator-observer-singleton-strategy/
For understanding I´ve cutted it a bit down:
interface IStrategy
{
public function execute();
}
class PayCash implements IStrategy
{
public function execute()
{
echo "Paying via Cash";
}
}
class Payment
{
private $_strategy; // new PayCash()
public function __construct(IStrategy $strategy)
{
$this->_strategy = $strategy;
}
public function execute()
{
$this->_strategy->execute(); // PayCash->execute();
}
}
//----------------------------------------------
$payment1 = new Payment(new PayCash());
$payment1->execute();
Questions:
What does (IStrategy do ? It works also without this.
public function __construct(IStrategy $strategy)
Does strategy pattern require to use interfaces? If I´m understanding correctly interfaces aim is to force classes to implement a method. I could write this also without interface ISstrategy but would it stay strategy pattern?
Thanks,
t book
It will stay pattern without Interface, but, you need to understand that interfaces is not only for forcing method implementation, it is also used in Type Hinting. Interfaces enforces its contract within classes to insure that a class has these methods.