php interface polymorph无法跟踪为什么执行函数

时间:2014-01-16 17:16:39

标签: php algorithm design-patterns

我正在测试使用接口和PHP。我能够在以下链接的帮助下找到从Java到Perl的“Head First Design Patterns”中重新创建鸭子设计问题的代码:

http://idhana.com/2011/10/12/design-pattern-strategy-in-php/

但是,我注意到创建者将quack()算法的名称更改为“Quacker()”。我不知道为什么会这样,但事实证明它可以解释我的问题。

当我将算法的名称保留为Quack而不是Quacker时,继承类的实例不仅设置了行为,还提交了它! (打印一些我不想看的文字,直到我命令鸭子这样做)

我有两只鸭子来测试它。一个使用Quack()和另一个QuackNormally()。我已经将文件创建到Duck_That_Quacks_Prematurely_At_Birth.php中,以显示Duck类的这个实例使用我不理解的行为和使用QuackNormally()算法的Duck_That_Quacks_Normally.php。

<?php

abstract class Duck
{
    protected $quackBehavior;

    public function performQuack()
    {
        $this->quackBehavior->quack();
    }
}
?>
<?php

include_once("QuackNormally.php");

class Duck_That_Quacks_Normally extends Duck
{
    public function __construct()
    {
        $this->quackBehavior = new QuackNormally();
    }

}

?>
<?php

include_once("Quack.php");

class Duck_That_Quacks_Prematurely_At_Birth extends Duck
{
    public function __construct()
    {
        $this->quackBehavior = new Quack();
    }
}

?>

<?php

interface QuackBehavior
{
    public function quack();
}

?>
<?php

include_once ("QuackBehavior.php");

class QuackNormally implements QuackBehavior
{
    public function quack()
    {
        echo ("This is a normal quack that you should not hear until ordered.");
    }
}
<?php

include_once ("QuackBehavior.php");

class Quack implements QuackBehavior
{
    public function quack()
    {
        echo ("QUACK !!! I can't stop talking once created !!!");
    }
}

?>

<?php

include_once ("Duck.php");
include_once ("Duck_That_Quacks_Prematurely_At_Birth.php");
include_once ("Duck_That_Quacks_Normally.php");

echo "<html>";

echo "Duck_That_Quacks_Prematurely_At_Birth being created:<br/>";
$test_duck = new Duck_That_Quacks_Prematurely_At_Birth();
#echo "Start of a break line:<br/>";
echo "<br/>";

echo "Duck_That_Quacks_Normally being created:<br/>";
$control_duck = new Duck_That_Quacks_Normally();
#echo "Start of a break line:<br/>";
echo "<br/>";

echo "Duck_That_Quacks_Prematurely_At_Birth wants to say something:<br/>";
$test_duck->performQuack();
#echo "Start of a break line:<br/>";
echo "<br/>";

echo "Duck_That_Quacks_Normally wants to say something:<br/>";
$control_duck->performQuack();
#echo "Start of a break line:<br/>";
echo "<br/>";

echo "</html>";

?>

我最好的选择是名称 - 鸭子类的quack()用同名的算法名称 - Quack()来破坏。然而,PHP是区分大小写的,所以老实说我不知道​​发生了什么。

我为外星人或烦人的词汇道歉。这是我的第一篇文章。感谢。

0 个答案:

没有答案