Patterns are especially useful for OOP developers because they help create stable APIs and remain flexible. A pattern can help us define the objects responsible for accomplishing a particular task, and it allows us to completely modify a class without modifying the code that deals with those classes. The former is called the function of the class, the latter being called the polymorphism of the class.
The singleton pattern is used as a duty pattern, and he uses it to create a single feature access point in the application. It delegates control over the creation of the object to a single access point. There is only one instance of this class that exists in the application at any given time. This prevents us from opening multiple connections to the database or using unnecessary system resources. In more complex systems, the use of a single case pattern is particularly useful in maintaining the synchronization of application state.
All the single instance classes have at least three common elements:
They must have a constructor and must be marked private.
They have a static member variable that holds an instance of the class.
They have a public static method to access this instance
Unlike ordinary classes, a singleton class cannot be instantiated directly in other classes. A singleton class can only be instantiated by itself. To obtain such a result, the __construct () method must be marked private. If you try to construct a class with the private constructor, you get an accessibility level error.
To make a singleton class work, you must give it an instance of the other class, and use it to invoke various methods. The Singleton class does not create a copy of the instance, but instead returns a reference to the instance stored within the Singleton class. The result is that the single example class does not duplicate memory and system resources, making it easier for other parts of the application to use those resources. As part of this pattern, you must create an empty private __clone () method to prevent the object from being copied or cloned.
This method of returning an instance reference is usually named Gettnstance (). This method must be static, and if it is not instantiated, it must be instantiated. The getinstance () method can detect whether a class has been instantiated by using the instanceof operator and the self keyword.
/* Example: Centralized control of database connection responsibilities * *
Class Database {
Private $_db;
Static $_instance;
Private Function __construct () {
$this->_db = pg_connect (' dbname=example_db ');
}
Private __clone () {};
public static function getinstance () {
if (! (Self::$_instance instanceof Self)) {
Self::$_instance = new self ();
}
return self::$_instance;
}
Public Function Query ($sql) {
Execute a query using $this->_db
Return Pg_query ($this->_db, $sql);
}
}