Friday, 26 February 2021

Singleton design pattern, and acheieve singleton in php

 Singleton 

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance. This is useful when exactly one object is needed to coordinate actions across the system. The term comes from the mathematical concept of a singleton. Wikipedia


https://betterprogramming.pub/what-is-a-singleton-2dc38ca08e92


Down side of singleton :

  1. They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.

  2. They violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle.

  3. They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.

  4. They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.


https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons

Java implementation 

Declaring a method static means it is a class method and can be called on the class without an instance (and can't access instance members because there's no object in context to use - no this).

Look at the code below. Expected output:

[1] Different
[2] Same

If you want a variable to have the lifetime of the class and return the same object every time also declare the variable as static in the class:

public static String getThing(){
    String r=new String("ABC");//Created every time the method is invoked.
    return r;
}

private static String sr=new String("ABC");//Static member - one for the whole class.

public static String getStaticThing(){
    return sr;
}

public static void main (String[] args) throws java.lang.Exception
{
    String thing1=getThing();
    String thing2=getThing();
    if(thing1==thing2){
        System.out.println("[1] Same");
    }else{
        System.out.println("[1] Different");
    }

    String thing1s=getStaticThing();
    String thing2s=getStaticThing();
    if(thing1s==thing2s){
        System.out.println("[2] Same");
    }else{
        System.out.println("[2] Different");
    }
}
https://stackoverflow.com/questions/46163755/are-values-returned-by-static-method-are-static

PHP Implementation 


	public static function singleton()
	{
		if ( static::$instance === NULL ) {
			$classname = get_called_class();
			static::$instance = new $classname;
		}

		return static::$instance;
	}








No comments:

Post a Comment