工厂方法模式及php实现


工厂方法模式:

  工厂方法模式(Factory Method Pattern)又称为工厂模式,也叫虚拟构造器(Virtual Constructor)模式或者多态工厂(Polymorphic Factory)模式,它属于类创建型模式。在工厂方法模式中,工厂父类负责定义创建产品对象的公共接口,而工厂子类则负责生成具体的产品对象,这样做的目的是将产品类的实例化操作延迟到工厂子类中完成,即通过工厂子类来确定究竟应该实例化哪一个具体产品类。

工厂方法模式包含如下角色:

  • Product:抽象产品
  • ConcreteProduct:具体产品
  • Factory:抽象工厂
  • ConcreteFactory:具体工厂

UML图:

  ../_images/FactoryMethod.jpg

适用性:

  当一个类不知道它所必须创建的对象的类的时候。

  当一个类希望由它的子类来指定它所创建的对象的时候。

  当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。

abstract class Fruit{

}
class Apple extends Fruit{
    function __construct(){
        echo "Apple";
    }
}

class Banana extends Fruit{
    function __construct(){
        echo "Banana";
    }
}

interface Factory{
    createFruit();
}

class AppleFactory implements Factory{
    function createFruit(){
        return new Apple();
    }
}
class BananaFactory implements Factory{
    function createFruit(){
        return new Banana();
    }
}                   
原文地址:https://www.cnblogs.com/yujon/p/5532808.html