单例模式
C++
饿汉
# include <iostream>
using namespace std;
class Singleton
{
private :
Singleton ( ) { cout << "单例对象创建!" << endl; } ;
Singleton ( const Singleton & ) ;
Singleton & operator = ( const Singleton & ) ;
~ Singleton ( ) { cout << "单例对象销毁!" << endl; } ;
static Singleton * myInstance;
public :
static Singleton * getInstance ( )
{
return myInstance;
}
static void releaseInstance ( )
{
delete myInstance;
}
} ;
Singleton * Singleton:: myInstance = new Singleton ( ) ;
int main ( )
{
Singleton * ct1 = Singleton :: getInstance ( ) ;
Singleton * ct2 = Singleton :: getInstance ( ) ;
Singleton * ct3 = Singleton :: getInstance ( ) ;
Singleton :: releaseInstance ( ) ;
return 0 ;
}
懒汉
# include <iostream>
using namespace std;
class Singleton
{
private :
Singleton ( ) { cout << "单例对象创建!" << endl; } ;
Singleton ( const Singleton & ) ;
Singleton & operator = ( const Singleton & ) ;
~ Singleton ( ) { cout << "单例对象销毁!" << endl; } ;
public :
static Singleton * getInstance ( )
{
static Singleton myInstance;
return & myInstance;
}
} ;
int main ( )
{
Singleton * ct1 = Singleton :: getInstance ( ) ;
Singleton * ct2 = Singleton :: getInstance ( ) ;
Singleton * ct3 = Singleton :: getInstance ( ) ;
return 0 ;
}
C
饿汉
# include <stdio.h>
typedef struct
{
int initialized;
} Singleton;
static Singleton singleton = { 1 } ;
Singleton * getSingleton ( void )
{
static Singleton * ptr = & singleton;
return ptr;
}
int main ( )
{
Singleton * ct1 = getSingleton ( ) ;
Singleton * ct2 = getSingleton ( ) ;
Singleton * ct3 = getSingleton ( ) ;
return 0 ;
}
懒汉
# include <stdio.h>
typedef struct
{
int initialized;
} Singleton;
static Singleton * getSingleton ( void )
{
static Singleton instance = { 0 } ;
static Singleton * ptr = NULL ;
if ( ptr == NULL )
{
ptr = & instance;
instance. initialized = 1 ;
printf ( "单例对象创建!\n" ) ;
}
return ptr;
}
int main ( )
{
Singleton * ct1 = getSingleton ( ) ;
Singleton * ct2 = getSingleton ( ) ;
Singleton * ct3 = getSingleton ( ) ;
return 0 ;
}