This example introduces the two most common examples in the singleton design model-the hungry and lazy Singleton.
1. Class Diagram
2. Java implementation code package cn.edu. ynu. Sei. Singleton;
/**
* "Hungry" Singleton class
*
* @ Author 88250
* @ Version 1.0.0, 2007-8-17
*/
Public class eagersingleton
{
/**
* Single Instance
*
* @ UML. property name = "instance" readonly = "true"
*/
Private Static final eagersingleton instance = new eagersingleton ();
/**
* Private default constructor
*/
Private eagersingleton ()
{
}
/**
* Static factory Method
*
* @ Return returns the instance.
*/
Public static eagersingleton getinstance ()
{
Return NULL;
}
}
Package cn.edu. ynu. Sei. Singleton;
/**
* "Lazy" Singleton
*
* @ Author 88250
* @ Version 1.0.0, 2007-8-17
*/
Public class lazysingleton
{
/**
* Single Instance
*
* @ UML. property name = "instance"
*/
Private Static lazysingleton instance;
/**
* Private default constructor
*/
Private lazysingleton ()
{
}
/**
* Static factory Method
* @ Return returns the instance.
* @ UML. property name = "instance"
*/
Public static lazysingleton getinstance ()
{
If (instance = NULL)
{
Instance = new lazysingleton ();
}
Return instance;
}
}
3. Summary
Here is just the simplest example. In the singleton mode, there is also a pattern called "Register-type" Singleton, this mode overcomes the disadvantages that none of the above two examples can inherit. If you are interested, you can check the relevant information by yourself. I will not go into details here. Here we will briefly discuss the issues that should be paid attention to when using the singleton mode in a distributed system and multi-threaded environment.
In a distributed system, the designed Singleton class may be instantiated in different JVMs, which is equivalent to the singleton mode with multiple instances globally. Note that if the Singleton is stateless, there is no problem. However, if this Singleton is stateful, it will cause some problems. For example, if a singleton object can hold an int type attribute and is used to provide a unique serial number of a value to a system as the billing number of a sales system, the user will see the same number appear several times. Therefore, the stateful Singleton mode should be avoided in any distributed system that uses technologies such as EJB, RMI, And Jini.
In a multi-threaded environment, you must use the synchronized keyword to synchronize the getinstance method. If you are an experienced C/C ++ programmer, you may use the code mode of "Double Check into example" to solve this problem. However, this code-level mode cannot be set up in Java at all. For more information about the dual-check examples, see Java and design patterns and [bloch01, goetz01, dcl01].
So the abstract factory only supports OCP to a certain extent, which deserves our attention during design.
4. References
Design Patterns and Java and Pattern