工厂模式是一种常见的设计模式,用于封装对象的创建过程。它通过定义一个公共接口来创建对象,但允许子类决定实例化哪个类。在 PHP 中,工厂模式可以通过类或方法实现。
//工厂类
//定义接口
interface Shape
{
public function draw();
}
//实现接口
class Circle implements Shape
{
public function draw()
{
echo "draw a Circle \n";
}
}
class Square implements Shape
{
public function draw()
{
echo "draw a Square \n";
}
}
class Rectangle implements Shape
{
public function draw()
{
echo "draw a Rectangle \n";
}
}
class ShapeFactory
{
public function getShape($class_name)
{
switch ($class_name) {
case 'Circle':
$rc = new ReflectionClass("Circle");
return $rc->newInstance();
case 'Square':
return new Square();
case 'Rectangle':
return new Rectangle();
default :
throw new Exception('类不存在!');
}
}
}$factory = new ShapeFactory();
$factory->getShape('Circle')->draw();
$factory->getShape('Square')->draw();
$factory->getShape('Rectangle')->draw();
网友评论