Single-instance mode C + + implementation
1 Description:
Singleton mode, also known as single-piece mode.
Definition: Ensure that a class has only one instance, and instantiate it itself and provide it to the entire system.
2 Concrete class Diagram Description:
2.1 STARTUML Internal generation pattern class diagram
This class diagram generates C + + code backwards by startuml
Class Singleton {
Public
Static singleton* Instance ();
Protected
Singleton ();
Private
Static Singleton *instance;
};
singleton* singleton::instance ()
{
if (instance==null)
Instance = new Singleton ();
return instance;
}
3. Detailed:
Based on the definition of the singleton pattern, the simplest way to achieve this requirement is to
① defines a global static object for use by the system.
② single-instance mode to achieve the requirements.
Note: These two parties are able to meet the demand, but, think of 6 principles: dependency inversion, interface isolation. Our design should be to rely on the interface, not the object, so long pass Diao ① bar.
4 Advantages and disadvantages of the single-case model:
Advantages: one instance reduces memory overhead, reduces system overhead, avoids multiple uses of a resource, sets global access points, optimizes and contributes resources.
Cons: No excuses, poor extensibility; not conducive to testing; there is a conflict with the single principle of responsibility, and the singleton model blends the "want Singleton" with the business logic in a class.
5 Usage Scenarios:
An environment that requires a unique serial number to be generated;
Share data or share access points;
Creating an object consumes too much resources, such as accessing the IO and database resources;
You need to define a large number of static constants and static methods (tool classes)
6 Thread safety issues
eg. when two threads run to if (instance==null), a thread-safety issue may occur
Improved resolution
Class Singleton {
Public
Static singleton* Instance ();
Protected
Singleton ();
Private
Static Singleton *instance;
};
The singleton is initialized directly, and no longer is judged in the method instance.
singleton* singleton::instance = new Singleton;
singleton* singleton::instance ()
{
return instance;
}
7 The expansion of the singleton mode--Multiple cases mode.
Class Singleton {
Public
Static singleton* Instance ();
Protected
Singleton ();
Private
Static Enum{max = 100};
static int curnum = 0;
Static List<singleton *>instance_list;
};
singleton* singleton::instance ()
{
Random random = new random ();
int count = Random.nextint (Max); Get random number
Return Instance_list.get (count);//random removal of an instance to use
}
8 questions
The initialization of a list in a multi-instance pattern is being tangled up, and finding a way to do so will add up.
Design pattern--a singleton mode C + + implementation