2013-05-30 133 views
0

我正在学习使用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. 
    } 
} 
+0

你为什么重新创建ConcreteCreator.php中的对象? '$ this-> createdProduct = new $ productNow;'只需使用'$ this-> createdProduct = $ productNow;'并且这可以解决您的问题 – Shaheer

+0

抱歉删除评论。从头开始。工厂用于创建具有相同父级的对象的更多指定实例,因此可以说您拥有图形父对象,它包含一些基本功能,如获取x和y,其x和y方法以及抽象绘制方法,比你将对象传递给创建者的字符串可以说“圆”,它将填充所有的absctract函数与圆类绘图等。至少这是我如何得到工厂模式。 – cerkiewny

+1

这不像工厂模式。在这个例子中,你自己创建了'Rectangle' *,通常你会传入类似于“矩形”的描述,工厂会自动创建。 – Jon

回答

0

的例子使用的工厂,让你HOWTO的想法去做

class Shape{ 
    int x,y 
} 

class Rectangle implements Shape{ 

} 

class Circle implements Shape{ 

} 
class ShapeCreator{ 
    public function create(string shapeName, int x, int y) { 
     switch(shapeName) 
      rectangle: 
       return new Rectangle(x,y) 
      circle: 
       return new Circle(x,y) 
    }  
} 
main{ 
    sc = new ShapeCreator 
    Shape circle = sc.create(1,2, "circle") 
} 

看其他概念看wikipedia有时工厂类的也只是一个接口将被不同类型的具体工厂所实现,但如果代码很简单,则可以使用该实例来实现对象的创建。

+0

我不喜欢你可以使用例如$ class = ucfirst(shapeName)的开关语句; if(class_exists($ class)return new $ class; – Sidux

+0

@sidux我认为这不是一个好主意,因为我们不确定“shapeName”是否是实现Shape的真实类,我也发现了更好的工厂使用示例[here](http://www.oodesign.com/factory-pattern.html) – cerkiewny

+0

什么是'circle'在main?什么是'sc'?我认为'sc'应该是'cs '但是仍然不知道这里的圆是什么,你没有创建任何圆的实例来使用它。 – 2619