Explanation:
As the object Creation Mode [gof95], the singleton mode ensures that a class has only one instance, and the instance is automatically instantiated to the entire system. This class is called a singleton class.
Singleton mode highlights:
1. A class can only have one instance
2. It must create its own instance
3. It must provide this instance to the entire system.
The Singleton mode can be divided into two categories:
Lazy and hungry
The Code is as follows:
/*** Hunger means hunger. Create */public class Singleton {Private Static Singleton instance = new Singleton (); public static Singleton getinstance () {return instance ;}}
/*** The lazy style is very lazy. When used, you can create **/public class Singleton {Private Static Singleton instance; Public synchronized static Singleton getinstance () {return instance = NULL? New Singleton (): instance; // creates a variable that does not exist, and the multi-threaded member variables that can be modified require security }}
Usage:
1. Read resource files and use more objects without repeating new
2. Cache
Advantage: Memory saving
Disadvantage: no polymorphism