Explanation of PHP Factory Mode Singleton Mode and Registry Tree Mode Examples

  • 2021-12-11 17:25:10
  • OfStack

In this paper, PHP factory pattern, singleton pattern and registry tree pattern are described as examples. Share it for your reference, as follows:

Three basic design patterns

1. Factory pattern: Factory methods or classes generate objects instead of new directly in code
2. Singleton mode: Only one object of a certain class is allowed to be created
3. Registration mode: Global sharing and exchange objects

Factory mode:


<?php
namespace IMooc;
class Factory
{
  static function createDatabase()
  {
    $db = new Database();
    return $db;
  }
}


$db = IMooc\Factory::createDatabase();

The advantage of factory mode is to avoid Database class, and carry out new operation in many php files. If Database class has changed (changed its name or parameters), then if it is not factory mode, it needs to be modified more. If you use factory mode, you only need to modify factory methods.

Singleton mode:


<?php
namespace IMooc;
class Database
{
  protected $db;
  private function __construct()
  {
  }
  //  Get an instance of a database operation 
  static function getInstance()
  {
    if(self::$db){
      return self::$db;
    }else{
      self::$db = new self();
      return self::$db;
    }
  }
}
//  No matter how many times it is called, , Will only create 1 Instances 
$db = IMooc\Database::getInstance();
$db = IMooc\Database::getInstance();
$db = IMooc\Database::getInstance();
$db = IMooc\Database::getInstance();

Registry tree mode:


<?php
namespace IMooc;
class Register
{
  protected static $objects;
  static function set($alias, $object)
  {
    self::$objects[$alias] = $object;
  }
  static function get($name)
  {
    return self::$objects[$name];
  }
  static function _unset($alias)
  {
    unset(self::$objects[$alias]);
  }
}
$db = \IMooc\Register::get('db1');

More readers interested in PHP can check out the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Syntax", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: