PHP를 사용하여 공장 패턴 디자인을 배우고 있습니다. 내 응용 프로그램은 Rectangle, Squares etc
과 같은 모양 이름과 x, y
위치와 같은 다른 모양 이름을 표시합니다. 첫 번째 사용자는 x 및 y 값을 제공하며이 값은 Rectangle(2, 2)
과 같이 모양 이름 옆에 표시됩니다.PHP 공장 패턴 디자인 문제
현재 코드의 문제는 모양 이름이 Rectangle
인데 사용자가 제공 한 x 및 y 값을 표시하지 않는다는 것입니다. 왜, 어떻게 x와 y 값을 표시 할 수 있습니까? 다음은
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();
내 코드 Product.php
다음abstract class Creator {
protected $createdProduct;
abstract public function factoryMethod(Product $productNow);
}
Creator.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();
}
}
ConcreteCreator.php
입니다입니다 여기공장의 예를 들어, 사용이
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보고보고 할 당신에게 하우투의 아이디어를 얻을 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 메서드 및 추상 그리기 메서드를 가져 오는 것과 같은 몇 가지 기본 함수가 포함되어 있다고 가정 해 볼 수 있습니다. 당신은 문자열을 가진 생성자에게 객체를 넘겨주는 것보다 "circle"이 circle 클래스 그리기 등과 같은 모든 absctract 함수를 채울 것이라고 말합니다. 적어도 이것이 공장 패턴을 얻는 방법입니다. – cerkiewny
이것은 공장 패턴과 아무런 관련이 없습니다. 위의 예에서'Rectangle' * yourself *를 만들 때, 일반적으로 "rectangle"설명과 같은 것을 전달할 것이고 factory는 생성을 할 것입니다. – Jon