What is Singleton pattern ?
- A simple design schema, in which, we instantiate object only once in a page life cycle.
Explanation with analogy.
- Lets say, you went to restaurant and ordered 3 types of Soup.
- Each Soup comes up with Bowl + Spoon
- Now, you have 3 spoons.
- Normal pattern : you use 3 spoons for each bowl
- problem in that: wastage of 3 spoons
-Singleton pattern: each time, you use: same spoon to drink soup.
- Thats it.
Real-time example:
- DB Object.
- We invoke DB object in page life cycle only once.
- Each time, we need to run query, we use same object.
Example with code:
}
Seems so easy :)
cheers!!!
- A simple design schema, in which, we instantiate object only once in a page life cycle.
Explanation with analogy.
- Lets say, you went to restaurant and ordered 3 types of Soup.
- Each Soup comes up with Bowl + Spoon
- Now, you have 3 spoons.
- Normal pattern : you use 3 spoons for each bowl
- problem in that: wastage of 3 spoons
-Singleton pattern: each time, you use: same spoon to drink soup.
- Thats it.
Real-time example:
- DB Object.
- We invoke DB object in page life cycle only once.
- Each time, we need to run query, we use same object.
Example with code:
class db{
publis static $_instance;
public static _getInstance(){
// Lets check, do we have object already instantiated ?
if(self::$_instance){
// return already instantiated object
return self::$_instance
}
else{
// else instantiate and return object
return self::$instance = new db();
}
}
}
Seems so easy :)
cheers!!!