2013-05-30 135 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