Singleton is one of the important design pattern in software development
Main objective of this pattern is , to create single instance of the class . Lets see how we are achieving that
class singleton
{
private
singleton() {}
public:
static singleton* CreateInstance() {
if(!instance )
{
instance = new singleton() ;
}
return instance ;
}
static singleton* instance ;
}
Important things you must know :
1. Why Constructor is private
-> So that , other class (outside of this class ) can't create the object .
2. Why we need static function ie static singleton* CreateInstance()
-> From first point , it is clear ,we can't create object of the class . So, static is the only way we can call function with out creating object of the class
3. Why member is static
-> As it is used inside the static function , It should be static
just google it , you will get more details about it
Advantage :
Using this pattern you are maintaining only one instance of this class
Setback :
1. This object is alive as long as application is alive
Main objective of this pattern is , to create single instance of the class . Lets see how we are achieving that
class singleton
{
private
singleton() {}
public:
static singleton* CreateInstance() {
if(!instance )
{
instance = new singleton() ;
}
return instance ;
}
static singleton* instance ;
}
Important things you must know :
1. Why Constructor is private
-> So that , other class (outside of this class ) can't create the object .
2. Why we need static function ie static singleton* CreateInstance()
-> From first point , it is clear ,we can't create object of the class . So, static is the only way we can call function with out creating object of the class
3. Why member is static
-> As it is used inside the static function , It should be static
just google it , you will get more details about it
Advantage :
Using this pattern you are maintaining only one instance of this class
Setback :
1. This object is alive as long as application is alive
No comments:
Post a Comment