Singleton
Singleton (Singleton Pattern) is one of the easiest in Java design patterns. This type of design pattern belongs create schema, which provides the best way to create objects. This model involves a single class that is responsible for creating your own objects, while ensuring that only a single object is created. This class provides the only way to access the object can directly access, no instance of the object class.
note:
- 1, only one singleton class instance.
- 2, singleton class must create their own unique instance.
- 3, singleton class must provide this example to all other objects
advantage:
- 1, only one instance in memory, reducing memory overhead, especially frequent create and destroy instances (such as School of Management Home page cache).
- 2. Avoid multiple assignment of resources (such as file write operations).
Cons: no interface, not inherited, and the conflict single responsibility principle, a class should only be concerned about the internal logic, not on the outside how to be instantiated.
achieve
We will create a SingleObject class. SingleObject class has its own private constructor and a static instance.
SingleObject class provides a static method, for the outside world to get its static instance. SingletonPatternDemo , our demo class uses SingleObject class to get SingleObject object.
step 1
Creating a Singleton class.
. 1 public class SingleObject { 2 . 3 // create an object of SingleObject . 4 Private static SingleObject instance = new new SingleObject (); . 5 . 6 // allow the constructor to private, so that the class can not be instantiated . 7 Private SingleObject () { } . 8 . 9 // Get the unique objects available 10 public static SingleObject the getInstance () { . 11 return instance; 12 is } 13 is 14 public void showMessage () { 15 System.out.println("Hello World!"); 16 } 17 }
Step 2
Get a unique object from singleton class.
. 1 public class SingletonPatternDemo { 2 public static void main (String [] args) { . 3 . 4 // illegal constructor 5 // compilation error: Constructor SingleObject () is not visible . 6 // SingleObject Object = new new SingleObject (); . 7 . 8 // Get the unique objects available . 9 SingleObject Object = SingleObject.getInstance (); 10 . 11 // display a message 12 is object.showMessage (); 13 is } 14 }
Step 3
The implementation of the program, output:
Hello World!
More real cases as a hungry man single-mode, single-mode example of a number of ways, want to understand the available data.
(Listed above knowledge and real self runoob.com description link: https: //www.runoob.com/design-pattern/singleton-pattern.html)