1. Single Case design mode
Make sure that there is only one instance of a class, and instantiate it yourself and provide this instance to the system as a whole
Elements:
@1. This class can have only one instance
@2. It must create this instance on its own
@3. It must provide this instance to the entire system on its own
Use:
@1. Mainly used for database applications, there will be a large number of database operations in an application, and then use the object-oriented approach to development, if using singleton mode, you can avoid a large number of new operations consumed by the resources, but also reduce the data base link
So it's not easy to too many connections situation
@2. If the system needs to have a class to control certain configuration information globally, it is convenient to use singleton mode, which can be referred to the frontcontroller part of the Zend Framework.
/** * Design mode single case mode *$_instance must be declared as a static private variable*constructors must be declared as privateTo prevent the external program new class from losing the meaning of a singleton pattern *The getinstance () method must be set to public, and this method must be called to return a reference to the instance *::Operators can only access static and static functions *new objects will consume memory* Usage Scenario: The most common place is the database connection. * Once an object is generated using singleton mode, the object can be used by many other objects. */class man{//Save example Instance private static $_instance in this attribute; The constructor is declared private, preventing direct creation of the object Private function __construct () {echo ' I was instantiated! ‘; }//Single-instance method Publicstatic functionget_instance() {//var_dump (Isset (self::$_instance)); if (!isset (self::$_instance)) {self::$_instance=new self (); } return self::$_instance; }//prevents the user from copying the object instance private function __clone () {Trigger_error (' clone is not allow ', e_user_error); } function Test () {echo ("test"); }}//This notation is error, because the constructor method is declared as private//$test = new man;//The following will get the example class of the Singleton object $test = Man::get_instance (); $test = man::get_ Instance (); $test->test ();//Copying an object will result in a e_user_error.//$test _clone = Clone $test;
Common design Patterns