0

我正在使用 php 学习工厂模式设计。我的应用程序所做的是显示不同的形状名称,例如Rectangle, Squares etc它们的x, y位置。第一个用户将提供 x 和 y 值,它将显示在形状名称旁边,例如这样Rectangle(2, 2)

我当前代码的问题在于它确实显示了形状名称,即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.
    }
}
4

1 回答 1

0

使用工厂的示例让您了解如何做

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有时 Factory 类将只是一个接口,它将由不同类型的具体工厂实现,但如果代码很简单,您可以使用案例来实现对象的创建。

于 2013-05-30T08:12:41.560 回答