I am going to interview a game company today. The pen test is called Designing and implementing a singleton base class. I have not seriously considered this issue before, And I have reprinted an article.
Address: http://blog.csdn.net/Blue_Light/archive/2008/07/13/2646266.aspx
In the creation mode, there is a design mode "Singleton ". The intention of this mode is to ensure that a class has only one instance and provide a global access point to access it. Under the guidance of gof, we often write some Singleton classes. Each class is similar.
BelowCodeDescribes a basic class of singleton and Its Usage:
Template<ClassT>
ClassAllocusingnew
{
Public:
StaticT * Create ()
{
Return NewT;
}
Static VoidDestroy (T * P)
{
DeleteP;
}
};
Template<ClassT>
ClassAllocusingstatic
{
Public:
StaticT * Create ()
{
StaticT;
Return New(& T) T;
}
Static VoidDestroy (T * P)
{
P-> ~ T ();
}
};
Template<ClassT,Template<Class>ClassAllocpolicy = allocusingstatic>
ClassSingleton
{
Public:
StaticT * instance ()
{
If(Null = m_pthis)
{
M_pthis = allocpolicy <t>: Create ();
Assert (m_pthis );
M_pthis-> initialize ();
}
ReturnM_pthis;
}
Static VoidDestroy ()
{
If(M_pthis)
{
M_pthis-> finalize ();
Allocpolicy <t >:: destroy (m_pthis );
M_pthis = NULL;
}
}
VoidInitialize ()
{
}
VoidFinalize ()
{
}
Protected:
Singleton (){}
~ Singleton (){}
Private:
Singleton (ConstSingleton &);
Singleton &Operator= (ConstSingleton &);
Friend ClassAllocpolicy <t>;
Private:
StaticT * m_pthis;
};
Template<ClassT,Template<Class>ClassAllocpolicy>
T * Singleton <t, allocpolicy>: m_pthis = NULL;
ClassMysingleton:PublicSingleton <mysingleton, allocusingnew>
{
Public:
VoidSetvalue (IntValue)
{
M_value = value;
}
VoidPrint ()
{
Cout <m_value <Endl;
}
VoidInitialize ()
{
M_value = 1000;
}
Private:
IntM_value;
};
Int_ Tmain (IntArgc, _ tchar * argv [])
{
Mysingleton: instance ()-> Print ();
Mysingleton: Destroy ();
System ("pause ");
Return0;
}