Definition of singleton pattern

Ensure that there is only one instance of a class , Cannot duplicate instances , It can only instantiate itself , And provide this instance to the whole system .

Problem solved

That is, a class is instantiated only once , When someone else instantiates it again , Returns the first instantiated object , Can avoid a lot of new operation , Reduce resource consumption .

principle : Four steps , Three private and one public

* Privatization static properties
* Construction method of privatization
* Privatization cloning method
* Static method of public ownership
Packaging background

When there are multiple singleton classes in a project , Every new class , We have to define "three private and one public" , It's a bit repetitive , It's not just a waste of time and energy , And the code is bloated and difficult to maintain , Is there any More elegant How to write it ?

Trait To encapsulate the singleton
php It has been a single inheritance language from before to now , Properties and methods cannot be inherited from both base classes , To solve this problem ,php Out Trait This feature
usage : By using use keyword , Declare the Trait name , concrete Trait Statement use of Trait key word ,Trait Cannot be instantiated .

Code Examples

Create a Trait
<?php /** * Trait Singleton Singleton mode */ Trait Singleton { private static $instance
= null; private function __construct() { parent::__construct(); // Construction method of privatization }
private function __clone() { // Privatization cloning method } public function __sleep() {
// rewrite __sleep method , Leave the return empty , Prevent serialization and deserialization from getting new objects return []; } public static function
getInstance() { if (!isset(self::$instance)) { self::$instance = new
static();// Not here new self(),self and static difference } return self::$instance; } }
Multiple inheritance usage
Other classes are used only in code use Singleton; , You can inherit the singleton <?php /** * Desc: Business 1 Inheritance instance */ class YieWu1
{ use Singleton; // Key line of code public function getInfo(){ // Business code } } <?php /** *
Desc: Business 2 Inheritance instance */ class YieWu2 { use Singleton; // Key line of code public function
getInfo(){ // Business code } }
Real column call
YieWu1::getInstance()->getInfo(); YieWu2::getInstance()->getInfo();

©2020 ioDraw All rights reserved
Vue The difference between single page and multi page 0.96OLED display -4 Line SPI explain R In language Axis() Detailed explanation of function parameters JAVA Snake games ( Source code + notes )C++ vector Simulation Implementation of class javascript Adding and deleting form information CCF A series of questions --2016 year 4 Month 1 Calculation of break point postman Interface test get timestamp and MD5 encryption 【 Recommended benefits 】c++ use easyx Making pixel birds , Simple hands on games TCP/IP There are so many loopholes in the agreement ?