php设计模式之工厂模式

工厂模式是用工厂方法代替new操作产生实例的一种模式。使用工厂模式的好处是,类实例化在工厂类中进行,如果你想要更改所实例化的类名和参数等,则只需更改该工厂方法代码即可。工厂模式为系统结构提供灵活的动态扩展机制,减少了耦合性。

定义一个接口类,并将其实现

<?php

interface IWorker
{
    public function getName();
}

class Worker1 implements IWorker
{
    public function getName()
    {
        // TODO: Implement getName() method.
        return "my name is name1\n";
    }
    public function setName($name)
    {
        // TODO: Implement setName() method.
    }
}
class Worker2 implements IWorker
{
    public function getName()
    {
        // TODO: Implement getName() method.
        return "my name is name2\n";
    }
    public function setName($name)
    {
        // TODO: Implement setName() method.
    }
}
class Worker3 implements IWorker
{
    public function getName()
    {
        // TODO: Implement getName() method.
        return "my name is name3\n";
    }
    public function setName($name)
    {
        // TODO: Implement setName() method.
    }
}

实现简单工厂

<?php

class SimpleFactory
{
    public static function getWorker($workerName)
    {
        if ($workerName == 1){
            return new Worker1();
        } elseif ($workerName == 2){
            return new Worker2();
        } elseif ($workerName == 3){
            return new Worker3();
        }
    }
}

测试简单工厂

<?php

$worker1 = SimpleFactory::getWorker(1);
echo $worker1->getName();
$worker2 = SimpleFactory::getWorker(2);
echo $worker2->getName();

输出

my name is name1
my name is name2

实现工厂方法

<?php

interface IFactory
{
    public function getWorker();
}
class Worker1Factory implements IFactory
{
    public function getWorker()
    {
        // TODO: Implement getWorker() method.
        return new Worker1();
    }
}
class Worker2Factory implements IFactory
{
    public function getWorker()
    {
        // TODO: Implement getWorker() method.
        return new Worker2();
    }
}

测试工厂方法

<?php

$worker1Factory = new Worker1Factory();
echo $worker1Factory->getWorker()->getName();
$worker2Factory = new Worker2Factory();
echo $worker2Factory->getWorker()->getName();

输出

my name is name1
my name is name2

以上便是简单工厂和工厂方法的实现和测试。