Zen-singleton mode in Design Mode
Personal blog this blog address: http://www.sanyinchenblog.com /? P = 233
Singleton mode:
Make sure that a class has only one instance, and instantiate it and provide the instance to the entire system.
Demo (https://github.com/sanyinchen/UMLDemo)
General View (hunger style ):
Single sample Common Code Template:
public class Singleton{private static final Singleton singleton=new Singleton();private Singleton(){}public static Singleton getSingleton(){return singleton;}public static void soSomthing(){}}
Here is an example of an emperor's worship: the emperor needs to receive and handle government affairs from the Emperor every day, and the Emperor needs to bow to the Emperor every day. The Emperor is the only Singleton.
Minister class:
Package com. sanyinchen. singleon; public class Emperor {private static Emperor emperor = null; private Emperor () {} public synchronized static Emperor getInstance () {if (emperor = null) {emperor = new Emperor ();} return emperor;} public void say () {System. out. println ("I'm the emperor .... ");}}
Emperor class:
Package com. sanyinchen. singleon; public class Emperor {private static Emperor emperor = null; private Emperor () {} public synchronized static Emperor getInstance () {if (emperor = null) {emperor = new Emperor ();} return emperor;} public void say () {System. out. println ("I'm the emperor .... ");}}
Running result:
I am the Emperor .... I am the Emperor .... I am the Emperor .... I am the Emperor .... I am the Emperor .... I am the Emperor .... I am the Emperor .... I am the Emperor .... I am the Emperor .... I am the Emperor ....
The preceding Singleton mode is lazy, and there is also a lazy style, which is to initialize the object directly during definition and return the object directly.
Advantages of Singleton mode:
(1) reduce memory expenses
(2) reduce system performance overhead
(3) Avoid multiple resource occupation
(4) optimizing and sharing resources
Disadvantages of Singleton mode:
(1) The Singleton mode generally has no interface, making expansion difficult.
(2) Countermeasures Against the singleton mode are unfavorable.
(3) The Singleton mode conflicts with the single responsibility principle.