【发布时间】:2024-12-09 12:05:01
【问题描述】:
我试图理解 PHP 中的策略模式。我的示例基于本教程:http://www.d-mueller.de/blog/5-php-patterns-im-schnelldurchlauf-factory-iterator-observer-singleton-strategy/
为了理解,我把它删减了一点:
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();
问题:
-
(IStrategy 有什么作用?没有这个也可以。
公共函数__construct(IStrategy $strategy)
策略模式是否需要使用接口?如果我理解正确,接口的目的是强制类实现一个方法。我也可以在没有接口 ISstrategy 的情况下编写此代码,但它会保持策略模式吗?
谢谢,
书
【问题讨论】:
-
你基本上是在问什么是接口......!?
标签: php strategy-pattern