Singleton pattern

Singleton pattern

is a creational pattern – one of the three basic design pattern.

As the name describes, it’s something which deals with a single value or it works as a unique thing.

In programming, it’s a class which have only one object in the entire execution process.

According to a programming language, you’ll have to set up the class in such a way that only one object will be created in the entire process.

Prerequisites:

  • Basic programming knowledge.
  • A basic oops concept like what is class, method, property, etc.
  • More understandable if you know PHP

In this, I’m going to use PHP as a programming language to implement the singleton pattern.

  • Make constructor – __contruct method – private.
  • Make __clone method private or keep it public, but let you always return $this variable.
  • Define a public static method to create an object of the same class.
  • Define a private static variable to check if the object created or not. Or keep the created object in that variable and return the same value if requested – I’m going to return the same object created in the previous call. I’ll create one if it’s called first time, and I’ll store it in the static variable.

 

  1. <?php
  2.  
  3. /**
  4.  * Description of SingletonPattern
  5.  *
  6.  * @author Ahmad Asjad <ahmadcimage@gmail.com>
  7.  */
  8. class SingletonPattern {
  9.  
  10. public $param1;
  11. public $param2;
  12. private static $selfInstance;
  13.  
  14. private function __construct($param1, $param2) {
  15. $this->param1 = $param1;
  16. $this->param2 = $param2;
  17. }
  18.  
  19. public function __clone() {
  20. return $this;
  21. }
  22.  
  23. /**
  24.   * @param string $param1
  25.   * @param string $param2
  26.   * @return SingletonPattern
  27.   */
  28. public static function getInstance($param1, $param2) {
  29. if (empty(self::$selfInstance)) {
  30. //Pass params to be passed to the constructor
  31. self::$selfInstance = new static($param1, $param2);
  32. }
  33. return self::$selfInstance;
  34. }
  35.  
  36. }

 

 

Leave a Reply