PHP中的工厂设计模式是什么? [英] What is a Factory Design Pattern in PHP?
问题描述
以最简单的说法,这使我感到困惑.假装您几乎在向母亲或某人解释.
This confuses me, in the most simplest terms what does it do? Pretend you are explaining to your mother or someone almost please.
推荐答案
工厂创建对象.因此,如果您想构建
A factory creates an object. So, if you wanted to build
class A{
public $classb;
public $classc;
public function __construct($classb, $classc)
{
$this->classb = $classb;
$this->classc = $classc;
}
}
您不想每次创建对象时都必须执行以下代码
You wouldn't want to rely on having to do the following code everytime you create the object
$obj = new ClassA(new ClassB, new Class C);
这就是工厂的所在地.我们定义了一个工厂来为我们处理这些事情:
That is where the factory would come in. We define a factory to take care of that for us:
class Factory{
public function build()
{
$classc = $this->buildC();
$classb = $this->buildB();
return $this->buildA($classb, $classc);
}
public function buildA($classb, $classc)
{
return new ClassA($classb, $classc);
}
public function buildB()
{
return new ClassB;
}
public function buildC()
{
return new ClassC;
}
}
现在我们要做的就是
$factory = new Factory;
$obj = $factory->build();
真正的优势在于您想更改班级.可以说我们想传递不同的ClassC:
The real advantage is when you want to change the class. Lets say we wanted to pass in a different ClassC:
class Factory_New extends Factory{
public function buildC(){
return new ClassD;
}
}
或新的ClassB:
class Factory_New2 extends Factory{
public function buildB(){
return new ClassE;
}
}
现在,我们可以使用继承来轻松地修改类的创建方式,以放置不同的类集.
Now we can use inheritance to easily modify how the class is created, to put in a different set of classes.
一个很好的例子可能是该用户类:
A good example might be this user class:
class User{
public $data;
public function __construct($data)
{
$this->data = $data;
}
}
在该类中,$data
是我们用于存储数据的类.现在,对于该类,可以说我们使用Session来存储数据.工厂看起来像这样:
In this class $data
is the class we use to store our data. Now for this class, lets say we use a Session to store our data. The factory would look like this:
class Factory{
public function build()
{
$data = $this->buildData();
return $this->buildUser($data);
}
public function buildData()
{
return SessionObject();
}
public function buildUser($data)
{
return User($data);
}
}
现在,可以说我们想将所有数据存储在数据库中,更改它真的很简单:
Now, lets say instead we want to store all of our data in the database, it is really simple to change it:
class Factory_New extends Factory{
public function buildData()
{
return DatabaseObject();
}
}
工厂是一种设计模式,我们可以用来控制如何将对象放在一起,使用正确的工厂模式可以创建所需的自定义对象.
Factories are a design pattern we use to control how we put objects together, and using correct factory patterns allows us to create the customized objects we need.
这篇关于PHP中的工厂设计模式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!