示例#1
0
{
    // use getShape method to get object of type Shape
    public function getShape($shapeType)
    {
        if (empty($shapeType)) {
            return NULL;
        }
        if (strtoupper($shapeType) == "CIRCLE") {
            return new Circle();
        } else {
            if (strtoupper($shapeType) == "RECTANGLE") {
                return new Rectangle();
            } else {
                if (strtoupper($shapeType) == "SQUARE") {
                    return new Square();
                }
            }
        }
        return NULL;
    }
}
$shapeFactory = new ShapeFactory();
// get an object of type Circle and call its draw method.
$shape1 = $shapeFactory->getShape("CIRCLE");
$shape1->draw();
// get an object of type Rectangle and call its draw method.
$shape2 = $shapeFactory->getShape("RECTANGLE");
$shape2->draw();
// get an object of type Square and call its draw method.
$shape3 = $shapeFactory->getShape("SQUARE");
$shape3->draw();
示例#2
0
<?php

require_once 'ShapeFactory.php';
require_once 'Shape.php';
require_once 'Square.php';
require_once 'Circle.php';
require_once 'Rectangle.php';
$shapeFactory = new ShapeFactory();
$circle = $shapeFactory->getShape('CIRCLE');
$circle->draw();
$square = $shapeFactory->getShape('SQUARE');
$square->draw();
$rectangle = $shapeFactory->getShape('RECTANGLE');
$rectangle->draw();