Design patterns: effective solutions to problems. In fact, it is a thought.
1. Singleton design pattern.
The problem solved: It can ensure the uniqueness of objects of a class in memory. (Single instance)
Requirements for using the singleton design pattern: When the same configuration information object must be used for multiple programs, the uniqueness of the object needs to be ensured.
How to ensure object uniqueness? Solution steps:
2. Create an instance of this class in this class. 2. Create an object in this category through New.
3. Provide a method for other programs to obtain the object. 3. Define a public method to return the created object.
//饿汉式(开发时常用) class Single//类一加载,对象就已经存在了。 { private static Single s = new Single(); private Single(){} public static Single getInstance() { return s; } } //懒汉式(面试时常问,在多线程并发访问时候有可能导致不能保证不了对象的唯一性,存在安全隐患!) class Single2//类加载进来,没有对象,只有调用了getInstance方法时,才会创建对象。 //延迟加载形式。 { private static Single2 s = null; private Single2(){} public static Single2 getInstance() { if(s==null) s = new Single2(); return s; } } //调用类 class SingleDemo { public static void main(String[] args) { Single s1 = Single.getInstance(); Single s2 = Single.getInstance(); System.out.println(s1==s2); // Single ss = Single.s; //此处不采用这个是因为不可控,采用 Single.getInstance();可以传参数进行相应调用。 } }
The above is the basic introductory essay on Java (10) JavaSE version - Singleton Design Pattern. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!