Singleton Pattern Definition and Usage Analysis of PHP Design Pattern

  • 2021-12-04 18:15:30
  • OfStack

This paper analyzes the singleton pattern of PHP design pattern with examples. Share it for your reference, as follows:

Singleton pattern (Singleton Pattern singleton pattern or single element pattern) is a common design pattern, which has three characteristics

1. There can only be 1 instance 2. You must create this instance yourself 3. You must provide this 1 instance to other objects

The following uses PHP code to realize 1


<?PHP
/**
 * Created by PHPStorm.
 * User: tiansi
 * Date: 18/1/2
 * Time:  Afternoon 3:40
 */
class Signleton{
  private static $_instanse = null;
  // Privatization construction method   Prevent external use new Instantiate object 
  private function __construct()
  {
  }
  // Privatized cloning method   Prevent external cloning of objects 
  private function __clone()
  {
    // TODO: Implement __clone() method.
  }
  // Static   Provide singleton access entry 
  static function getInstance(){
    if (is_null(self::$_instanse) || !isset(self::$_instanse)){
      self::$_instanse = new self();
    }
    return self::$_instanse;
  }
  public function say(){
    echo 'I am signleton';
  }
}

Next interview 1 is called


<?PHP
/**
 * Created by PHPStorm.
 * User: tiansi
 * Date: 18/1/2
 * Time:  Afternoon 3:48
 */
// No. 1 1 There are ways to report errors   Because the construction method is privatized 
//PHP Fatal error: Uncaught Error: Call to private Signleton::__construct() from invalid context in /Users/apple/uxin/SignletonController.PHP:11
/*
$signleton1 = new Signleton();
$signleton1->say();
*/
// The above code reports an error: Fatal error: Call to private Signleton::__construct() 
// Successful instantiation   Output I am signleton
$signleton2 = Signleton::getInstance();
$signleton2->say();

Run results:

I am signleton

Its advantages and disadvantages

Advantages:

1. In the singleton pattern, the active singleton has only one instance, and all instantiations of the singleton class result in the same one instance. This prevents other objects from instantiating themselves and ensures that all objects access one instance 2. The singleton pattern has a certain scalability, and the class controls the instantiation process by itself, so the class has corresponding scalability in changing the instantiation process. 3. Provides controlled access to only 1 instances. 4. Because there is only one object in the system memory, it can save system resources, and singleton mode can undoubtedly improve system performance when objects need to be created and destroyed frequently. 5. Allow a variable number of instances. 6. Avoid multiple occupations of shared resources.

Disadvantages:

1. Not applicable to changing objects. If objects of the same type 1 always change in different use case scenarios, singleton will cause data errors and cannot save each other's state. 2. Since there is no abstraction layer in the simple benefit pattern, it is very difficult to extend singleton classes. 3. The responsibility of singleton class is too heavy, which violates the principle of "single 1 responsibility" to a certain extent. 4. Abuse of singleton will bring some negative problems. For example, in order to save resources, the database connection pool object is designed as a singleton class, which may lead to too many programs sharing the connection pool object and lead to connection pool overflow; If the instantiated object is not used for a long time, the system will recycle it as garbage, which will lead to the loss of object state.

This is the advantage and disadvantage of singleton pattern, because the singleton pattern of PHP is different because of different language types

As we all know, PHP language is an interpretive scripting language. This running mechanism makes every PHP page be interpreted and executed, and all related resources will be recycled. That is to say, PHP has no way to make an object resident in memory at the language level, which is different from asp. net, Java and other compiled types. For example, in Java, a single case meeting 1 exists directly in the whole application life cycle, and variables are cross-page level, which can really achieve the uniqueness of this instance in the application life cycle. However, in PHP, All variables, whether global variables or static members of a class, They are all page-level. Every time a page is executed, new objects will be re-established and will be emptied after the page is executed. It seems that PHP singleton mode is meaningless, so PHP singleton mode is only useful when multiple application scenarios appear in a single page-level request and the same object resources need to be shared

For example

1. The application interacts with the database

There will be a large number of database operations in an application, such as connecting to the database through the database handle. Using singleton mode can avoid a large number of database operations new Operation, because every new operation consumes memory resources and system resources.

2. Control configuration information

If there is a class in the system to control some configuration information globally, it can be implemented conveniently by using singleton pattern

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

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


Related articles: