The three most common design patterns for all object-oriented objects are: Factory mode, Singleton mode, registration (device) mode
Factory mode, factory method or class to produce objects, hundred not directly in the code new
Singleton mode, which allows an object of a class to create only one
Registration mode, global sharing and exchanging objects
Factory mode factory.php
<?phpclass database{public function __construct () { return ' database\n '; } } Factory class factory{public static function CreateDatabase () { $db = new Database (); return $db; }} $db = Factory::createdatabase (); $db 1 = factory::createdatabase (); $db 2 = Factory::createdatabase (); Var_dump ($db, $db 1, $db 2), #object (database) #1 (0) {#} #object (database) #2 (0) {#} #object (database) #3 (0) {#}
Single case Mode singleton.php
<?php//single case mode class database{ protected static $db; The construction method is private and prevents the outer layer from being directly new private function __construct () { //code } static function getinstance () { if (Self:: $db) { return self:: $db; } else{self :: $db = new self (); Return self:: $db;}} } $db = Database::getinstance (); $db 1 = database::getinstance (); $db 2 = Database::getinstance (); Var_dump ($db, $db 1, $db 2), #object (database) #1 (0) {#} #object (database) #1 (0) {#} #object (database) #1 (0) {#}
Factory mode and single case combined use
<?phpclass database{ protected static $db; Private Function __construct () { } static function getinstance () { if (self:: $db) { return self:: $db; } else{self :: $db = new self (); Return self:: $db;}} } Class factory{public static function CreateDatabase () { return database::getinstance (); }} var_dump ( Factory::createdatabase ());
Registrar class register.php
<?php//registrar mode class register{ protected static $objects; static function set ($alias, $object) {self :: $objects [$alias] = $object; } static function Get ($name) { return self:: $objects [$name]; } function _unset ($alias) { unset (self:: $objects [$alias]);} } Register::set (' db1 ', $db); Register::get (' db1 ');