当导师向挑战提出这个解决方案时,我正在观看Lynda.com PHP设计模式教程:
的index.php:
include_once 'decorator.php';
$object = new Decorator();
$object->sentence = "This is a sample sentence that we're going to manipulate in the Decorator.";
// This should output: this is a sample sentence that we're going to manipulate in the decorator.
echo $object->lower();
// This should output: THIS IS A SAMPLE SENTENCE THAT WE'RE GOING TO MANIPULATE IN THE DECORATOR.
echo $object->uppercase();
decorator.php:
class Decorator
{
public $sentence = '';
public function lower()
{
return strtolower($this->sentence);
}
public function uppercase()
{
return strtoupper($this->sentence);
}
}
为什么这是一个装饰模式?我只看到对象的实例化并访问两个对象方法。
答案 0 :(得分:1)
您发布的示例不是装饰器,它只是在字符串顶部提供新界面(lower
和uppercase
)。装饰器在不改变底层接口的情况下添加行为。
装饰器的典型示例是字面上装饰图形元素。例如:
interface Shape {
draw();
}
class Rectangle implements Shape { ... }
class Circle implements Shape { ... }
class BorderDecorator implements Shape {
Shape shape;
draw() {
shape.draw();
drawBorder();
}
}
上面的所有类都有相同的接口,所以如果一个函数需要Shape
,你可以传入一个普通的Rectangle
或者你可以将它包装在BorderDecorator
中得到一个带边框的矩形。
答案 1 :(得分:0)
你所做的不是装饰者模式。如果您真的想将实用程序类转换为decorator,那么您刚刚为字符串创建了Utility类,然后只看到下面的内容:
<?php
interface StringInterface
{
public function string();
}
class StringDecorator implements StringInterface
{
private $text;
public function __construct($text)
{
$this->text = $text;
}
public function string()
{
return $this->text ;
}
}
class StringLower implements StringInterface
{
private $text;
public function __construct(StringInterface $text)
{
$this->text = $text;
}
public function string()
{
return strtolower( $this->text );
}
}
class StringUpper implements StringInterface
{
private $text;
public function __construct(StringInterface $text)
{
$this->text = $text;
}
public function string()
{
return strtoupper( $this->text );
}
}
class StringTrim implements StringInterface
{
private $text;
public function __construct(StringInterface $text)
{
$this->text = $text;
}
public function string()
{
return trim( $this->text );
}
}
// For Lowercase
$decorator=new StringLower( new StringDecorator("Text") );
// Output: Lowercase Text to text
$text=$decorator->string();
// For Uppercase
$decorator= new StringUpper( new StringDecorator("text") );
// Output: Uppercase text to Text
$text=$decorator->string();
//TO normalized text from " TeXT " to text.
$decorator= new StringTrim( new StringLower( new StringDecorator(" TeXT ") ) );
// Output: normalized text from " TeXT " to text also extra space removed from left and right.
$text=$decorator->string();
这是您的案例示例如果您需要更多真实世界的示例,请参阅here,我在这里给出了来自现实世界的好例子。