PHP 中的工厂设计模式是什么?

发布于 2024-08-18 08:36:07 字数 48 浏览 4 评论 0原文

这让我很困惑,用最简单的术语来说,它有什么作用?假装你正在向你的母亲或其他人解释。

This confuses me, in the most simplest terms what does it do? Pretend you are explaining to your mother or someone almost please.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

断爱 2024-08-25 08:36:07

工厂创建一个对象。因此,如果您想构建,

 class A{
    public $classb;
    public $classc;
    public function __construct($classb, $classc)
    {
         $this->classb = $classb;
         $this->classc = $classc;
    }
  }

您不会希望每次创建对象时都必须执行以下代码,

$obj = new ClassA(new ClassB, new Class C);

这就是工厂的用武之地。我们定义一个工厂来为我们处理这个问题:

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:

class Factory_New extends Factory{
    public function buildC(){
        return new ClassD;
    }
}

或一个新的 ClassB:

class Factory_New2 extends Factory{
    public function buildB(){
        return new ClassE;
    }
}

现在我们可以使用继承来轻松修改类的创建方式,以放入一组不同的类。

一个很好的例子可能是这个用户类:

class User{
    public $data;
    public function __construct($data)
    {
        $this->data = $data;
    }
}

在这个类中 $data 是我们用来存储数据的类。现在对于这个类,假设我们使用会话来存储数据。工厂看起来像这样:

class Factory{
    public function build()
    {
        $data = $this->buildData();
        return $this->buildUser($data);
    }

    public function buildData()
    {
        return SessionObject();
    }

    public function buildUser($data)
    {
        return User($data);
    }
}

现在,假设我们想要将所有数据存储在数据库中,更改它非常简单:

class Factory_New extends Factory{
    public function buildData()
    {
        return DatabaseObject();
    }
}

工厂是一种设计模式,我们用来控制如何将对象组合在一起,并使用正确的方法工厂模式允许我们创建我们需要的定制对象。

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;
    }
}

Now all we have to do is

$factory = new Factory;
$obj     = $factory->build();

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;
    }
}

or a new 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;
    }
}

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.

落日海湾 2024-08-25 08:36:07

当您处理多个资源并想要实现高级抽象时,工厂设计模式非常好。

让我们把它分成不同的部分。

假设您必须实现抽象,并且类的用户不需要关心您在类定义中实现的内容。

他/她只需要担心你的类方法的使用。

例如,您的项目有两个数据库,

class MySQLConn {

        public function __construct() {
                echo "MySQL Database Connection" . PHP_EOL;
        }

        public function select() {
                echo "Your mysql select query execute here" . PHP_EOL;
        }

}

class OracleConn {

        public function __construct() {
                echo "Oracle Database Connection" . PHP_EOL;
        }

        public function select() {
                echo "Your oracle select query execute here" . PHP_EOL;
        }

}

您的工厂类将负责创建数据库连接对象。

class DBFactory {

        public static function getConn($dbtype) {

                switch($dbtype) {
                        case "MySQL":
                                $dbobj = new MySQLConn();
                                break;
                        case "Oracle":
                                $dbobj = new OracleConn();
                                break;
                        default:
                                $dbobj = new MySQLConn();
                                break;
                }

                return $dbobj;
        }

}

用户只需要传递数据库类型的名称

$dbconn1 = DBFactory::getConn("MySQL");
$dbconn1->select();

输出:

MySQL Database Connection
Your mysql select query execute here

将来您可能有不同的数据库,那么您不需要更改整个代码,只需要传递新的数据库类型,其他代码将运行而不进行任何更改。

$dbconn2 = DBFactory::getConn("Oracle");
$dbconn2->select();

输出:

Oracle Database Connection
Your oracle select query execute here

希望这会有所帮助。

Factory design pattern is very good when you are dealing with multiple resources and want to implement high level abstraction.

Let's break this into different section.

Suppose you have to implement abstraction and the user of your class doesn't need to care about what you've implemented in class definition.

He/She just need to worry about the use of your class methods.

e.g. You have two databases for your project

class MySQLConn {

        public function __construct() {
                echo "MySQL Database Connection" . PHP_EOL;
        }

        public function select() {
                echo "Your mysql select query execute here" . PHP_EOL;
        }

}

class OracleConn {

        public function __construct() {
                echo "Oracle Database Connection" . PHP_EOL;
        }

        public function select() {
                echo "Your oracle select query execute here" . PHP_EOL;
        }

}

Your Factory class would take care of the creation of object for database connection.

class DBFactory {

        public static function getConn($dbtype) {

                switch($dbtype) {
                        case "MySQL":
                                $dbobj = new MySQLConn();
                                break;
                        case "Oracle":
                                $dbobj = new OracleConn();
                                break;
                        default:
                                $dbobj = new MySQLConn();
                                break;
                }

                return $dbobj;
        }

}

User just need to pass the name of the database type

$dbconn1 = DBFactory::getConn("MySQL");
$dbconn1->select();

Output:

MySQL Database Connection
Your mysql select query execute here

In future you may have different database then you don't need to change the entire code only need to pass the new database type and other code will run without making any changes.

$dbconn2 = DBFactory::getConn("Oracle");
$dbconn2->select();

Output:

Oracle Database Connection
Your oracle select query execute here

Hope this will help.

樱花坊 2024-08-25 08:36:07

就像现实生活中的工厂一样,它创造一些东西并返回它。

想象一下类似这样的东西

$joe = new Joe();
$joe->say('hello');

或工厂方法

Joe::Factory()->say('hello');

工厂方法的实现将创建一个新实例并返回它。

Like a real life factory, it creates something and returns it.

Imagine something like this

$joe = new Joe();
$joe->say('hello');

or a factory method

Joe::Factory()->say('hello');

The implementation of the factory method will create a new instance and return it.

不气馁 2024-08-25 08:36:07

实例化对象的经典方法是:

$Object=new ClassName();

PHP 能够使用以下语法从变量名动态创建对象:

$Object=new $classname;

其中变量 $classname 包含想要实例化的类的名称。

所以经典的对象分解看起来像:

function getInstance($classname)
{
  if($classname==='Customer')
  {
    $Object=new Customer();
  }
  elseif($classname==='Product')
  {
    $Object=new Product();
  }
  return $Object;
}

如果你调用 getInstance('Product') 函数,这个工厂将创建并返回 Product 对象。否则,如果您调用 getInstance('Customer') 函数,该工厂将创建并返回 Customer 类型对象(从 Customer() 类创建)。

不再需要这样做,可以将“Product”或“Customer”(现有类的确切名称)作为变量值发送以进行动态实例化:

$classname='Product';
$Object1=new $classname; //this will instantiate new Product()

$classname='Customer';
$Object2=new $classname; //this will instantiate new Customer()

The classic approach to instantiate an object is:

$Object=new ClassName();

PHP has the ability to dynamically create an object from variable name using the following syntax:

$Object=new $classname;

where variable $classname contains the name of class one wants to instantiate.

So classic object factoring would look like:

function getInstance($classname)
{
  if($classname==='Customer')
  {
    $Object=new Customer();
  }
  elseif($classname==='Product')
  {
    $Object=new Product();
  }
  return $Object;
}

and if you call getInstance('Product') function this factory will create and return Product object. Otherwise if you call getInstance('Customer') function this factory will create and return Customer type object (created from Customer() class).

There's no need for that any more, one can send 'Product' or 'Customer' (exact names of existing classes) as a value of variable for dynamic instantiation:

$classname='Product';
$Object1=new $classname; //this will instantiate new Product()

$classname='Customer';
$Object2=new $classname; //this will instantiate new Customer()
一花一树开 2024-08-25 08:36:07

一般来说,“工厂”会产生一些东西:在面向对象编程的情况下,“工厂设计模式”会产生对象。

无论是 PHP、C# 还是任何其他面向对象的语言都没关系。

In general a "factory" produces something: in the case of Object-Orientated-Programming, a "factory design pattern" produces objects.

It doesn't matter if it's in PHP, C# or any other Object-Orientated language.

葬﹪忆之殇 2024-08-25 08:36:07

工厂设计模式(Factory Pattern)是为了松耦合。就像工厂的含义一样,数据到工厂(生产数据)到最终用户。通过这种方式,工厂打破了数据源和数据过程之间的紧密耦合。

Factory Design Pattern (Factory Pattern) is for loose coupling. Like the meaning of factory, data to a factory (produce data) to final user. By this way, the factory break the tight coupling between source of data and process of data.

时光磨忆 2024-08-25 08:36:07

工厂只是生成一个或多个对象。

您可能有一个构建 MySQL 连接的工厂。

http://en.wikipedia.org/wiki/Factory_method_pattern

A factory just generates an object or objects.

You may have a factory that builds a MySQL connection.

http://en.wikipedia.org/wiki/Factory_method_pattern

喜爱纠缠 2024-08-25 08:36:07

这个答案与 Daniel White 所说的使用工厂来使用工厂模式创建 MySQL 连接的其他帖子有关。

对于 MySQL 连接,我宁愿使用单例模式,因为您想使用相同的连接
用于访问数据库而不是创建另一个数据库。

This answer is in relation to other post in which Daniel White said to use factory for creating MySQL connection using factory pattern.

For MySQL connection I would rather use singleton pattern as you want to use same connection
for accessing the database not create another one.

不奢求什么 2024-08-25 08:36:07

郑重声明,简单来说,像 @Pindatjuh 所说的工厂会返回一个对象。

那么,与构造函数有什么区别? (作用相同)

  1. 构造​​函数使用他自己的实例。
  2. 我想要一些更高级的东西,并且我不想使对象膨胀(或添加依赖项)。
  3. 创建每个实例时都会调用构造函数。有时您不希望这样。

    例如,假设每次我创建 Account 类的对象时,我都会从数据库读取一个文件并将其用作模板。

使用构造函数:

class Account {
      var $user;
      var $pwd;
      var ...
      public __construct() {
         // here i read from the file
         // and many other stuff
      }
}

使用工厂:

class Account {
      var $user;
      var $pwd;
      var ...
}
class AccountFactory {
      public static Create() {
         $obj=new Account();
         // here we read the file and more stuff.
         return $obj;
      }

For the record, in easy words, a factory like @Pindatjuh said, returns a object.

So, what's the difference with a constructor? (that does the same)

  1. a constructor uses his own instance.
  2. Something i want to so something more advanced and i don't want to bloat the object (or add dependencies).
  3. Constructor is called when each instance is created. Sometimes you don't want that.

    For example, let's say that every time i creates an object of the class Account, i read from the database a file and use it as a template.

Using constructor:

class Account {
      var $user;
      var $pwd;
      var ...
      public __construct() {
         // here i read from the file
         // and many other stuff
      }
}

Using factory:

class Account {
      var $user;
      var $pwd;
      var ...
}
class AccountFactory {
      public static Create() {
         $obj=new Account();
         // here we read the file and more stuff.
         return $obj;
      }
爱殇璃 2024-08-25 08:36:07

对于应用程序代码而言,工厂是一种易于维护和可扩展的解决方案。它解决了 SOLID 建议我们遵循的代码耦合问题。本质上是一种简化结构构建/创建的方法。它可以是一个对象、一个函数、一个数组。

只要您将使用结构的代码与创建它们的代码解耦并返回对象/结构,您就可以使用工厂,该工厂可以是以下四种之一:

  • 工厂方法
  • 抽象工厂
  • 静态工厂
  • 简单工厂

主要区别在于工厂方法和抽象工厂。

一个从一系列定义明确的元素生成对象/结构,另一个使用自己的分解策略生成对象的蓝图。

一种生成具体元素,另一种生成类型。

The factory is a solution for easy maintenance and scalability when it comes to your application code. It solves the code coupling issue that SOLID suggests we follow. Essentially is a way to simplify the build/creation of structures. It can be a object, a function, an array.

As long as you are decoupling code that uses the structure from code that creates them and returning objects/structures you are using a factory which can be one of the four :

  • Factory method
  • Abstract factory
  • Static factory
  • Simple factory

The main difference resides in the factory method and abstract factory.

One generates objects/structures from a list of well defined elements, the other generate the blueprints of objects with their own factoring strategies.

One generates concrete elements, the other generates types.

写下不归期 2024-08-25 08:36:07

工厂方法是一种创建型设计模式,它提供了在超类中创建对象的接口,但允许子类更改将创建的对象的类型。

最多花 30 分钟浏览此链接 工厂方法

稍后感谢我。

Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

Take a maximum of 30 mins and go through this link Factory Method

Thank me later.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文