php简单工厂模式


简单工厂模式

简单工厂模式最大的优点在于实现对象的创建和对象的使用分离,将对象的创建交给专门的工厂类负责,但是其最大的缺点在于工厂类不够灵活,增加新的具体产品需要修改工厂类的判断逻辑代码,而且产品较多时,工厂方法代码将会非常复杂。

代码

<?php

// 鼠标接口
interface Mouse
{
    public function click();
}

// dell鼠标
class DellMouse implements Mouse
{

    public function click()
    {
        echo "dell 鼠标单击".PHP_EOL;
    }

}

// 惠普鼠标
class HPMouse implements Mouse
{

    public function click()
    {
        echo  'hp 鼠标单击'.PHP_EOL;
    }
}

// 工厂 根据传入的值,返回不同对象
class SimpleFactory
{
    // 生产鼠标
    public static function createMouse(string $name)
    {
        if(strtoupper($name) == 'HP'){
            return new HPMouse();
        } else if(strtoupper($name) == "DELL"){
            return new DellMouse();
        }
    }
}

// 使用
$dellMouse = SimpleFactory::createMouse("dell");
$hpMouse = SimpleFactory::createMouse("hp");
$dellMouse->click();
$hpMouse->click();



<?php 
//简单工厂模式
class Cat
{
  function __construct()
  {
      echo "I am Cat class 
"; } } class Dog { function __construct() { echo "I am Dog class
"; } } class Factory { public static function CreateAnimal($name){ if ($name == 'cat') { return new Cat(); } elseif ($name == 'dog') { return new Dog(); } } } $cat = Factory::CreateAnimal('cat'); $dog = Factory::CreateAnimal('dog');
<?php

require './vendor/autoload.php';

use Swoole\Coroutine;
use function Swoole\Coroutine\run;


interface Mouse {
    public function click();
}

class Dell implements Mouse
{

    public function click()
    {
        var_dump("dell mouse");
    }
}

class Huawei implements Mouse
{

    public function click()
    {
        var_dump("huawei mouse");
    }
}

class FactoryMouse
{
    public static function createMouse($name)
    {
        if ($name == 'dell'){
            return new Dell();
        } elseif($name == 'huawei'){
            return new Huawei();
        }
    }
}

$dell = FactoryMouse::createMouse("dell");
$huawei = FactoryMouse::createMouse("huawei");
$dell->click();
$huawei->click();

相关