我正在学习使用php的工厂模式设计。我的应用程序所做的是显示不同的形状名称,例如Rectangle, Squares etc
及其x, y
职位。第一个用户将提供x和y值,它将与形状名称一起显示,例如像这样的Rectangle(2, 2)
。php工厂模式设计问题
我目前的代码存在的问题是,它确实显示了形状名称,即Rectangle
,但它没有显示用户提供的x和y值。为什么以及如何显示x和y值?
下面是我的代码 的index.php
include_once("ConcreteCreator.php");
class Client {
public function __construct() {
$shapeNow = new ConcreteCreator();
$display = $shapeNow->factoryMethod(new Rectangle(2, 2));
//Above I am passing x and y values in Rectangle(2, 2);
echo $display . '<br>';
}
}
$worker = new Client();
下面是ConcreteCreator.php
include_once('Creator.php');
include_once('Rectangle.php');
class ConcreteCreator extends Creator {
public function factoryMethod(Product $productNow) {
//echo $productNow;
$this->createdProduct = new $productNow;
return $this->createdProduct->provideShape();
}
}
下面是Creator.php
abstract class Creator {
protected $createdProduct;
abstract public function factoryMethod(Product $productNow);
}
下面是Product.php
interface Product {
function provideShape();
}
这里是Rectangle.php
include_once('Product.php');
class Rectangle implements Product {
private $x;
private $y;
//Here is I am setting users provided x and y values with private vars
public function __construct($x, $y) {
echo $x;
$this->x = $x;
$this->y = $y;
}
public function provideShape() {
echo $this->x; //Here x does not show up
return 'Rectangle (' . $this->x . ', ' . $this->y . ')';
//above x and y does not show up.
}
}
你为什么重新创建ConcreteCreator.php中的对象? '$ this-> createdProduct = new $ productNow;'只需使用'$ this-> createdProduct = $ productNow;'并且这可以解决您的问题 – Shaheer
抱歉删除评论。从头开始。工厂用于创建具有相同父级的对象的更多指定实例,因此可以说您拥有图形父对象,它包含一些基本功能,如获取x和y,其x和y方法以及抽象绘制方法,比你将对象传递给创建者的字符串可以说“圆”,它将填充所有的absctract函数与圆类绘图等。至少这是我如何得到工厂模式。 – cerkiewny
这不像工厂模式。在这个例子中,你自己创建了'Rectangle' *,通常你会传入类似于“矩形”的描述,工厂会自动创建。 – Jon