工厂方法模式

工厂方法模式

简单工厂模式违反了开闭原则还有单一职责原则,工厂方法模式是对简单工厂模式的进一步抽象。

工厂方法模式的优缺点
优点:

  1. 用户创建实例时不需要知道知道具体类,而只需要知道工厂类;
  2. 新建一个产品,只需要新建一个相应的类;

缺点:

  1. 类的个数将会越来越多;
  2. 增加系统抽象度,更加难以理解;
  3. 抽象产品只能生产一种产品。

具体代码
AbstractFactory.php




namespace App\Creational\Factory;


abstract class AbstractFactory
{
     
    abstract static public function make();
}

IphoneFactory.php




namespace App\Creational\Factory;


class IphoneFactory extends AbstractFactory
{
     
    static public function make(){
     
        return new Iphone();
    }
}

XiaomiFactory.php




namespace App\Creational\Factory;


class XiaomiFactory extends AbstractFactory
{
     
    static public function make(){
     
        return new Xiaomi();
    }
}

AbstractPhone

  



namespace App\Creational\Factory;


abstract class AbstractPhone
{
     

    abstract public function playMusic();

    abstract public function playVideo();
}

Xiaomi.php




namespace App\Creational\Factory;


class Xiaomi extends AbstractPhone
{
     
    public function playVideo()
    {
     
        // TODO: Implement playVideo() method.
    }

    public function playMusic()
    {
     
        // TODO: Implement playMusic() method.
    }

}

Iphone.php

  



namespace App\Creational\Factory;


class Iphone extends AbstractPhone
{
     
    public function playVideo()
    {
     
        // TODO: Implement playVideo() method.
    }

    public function playMusic()
    {
     
        // TODO: Implement playMusic() method.
    }

}

测试代码



class FactoryTest extends \PHPUnit\Framework\TestCase
{
     
    public function testPhoneProcut()
    {
     
        $phone = \App\Creational\Factory\IphoneFactory::make();
        $this->assertInstanceOf(\App\Creational\Factory\Iphone::class, $phone);
    }
}

你可能感兴趣的:(设计模式,PHP,设计模式)