单例模式:类在内存中仅存在一个实例
1.构造函数私有化,用private修饰
2.自行创建实例
3.对外提供一个公有的方法,返回这个实例
饿汉式:
package com.lqh.chapter03; public class _31singleton { public static void main(String[] args) { Singleton test1 = Singleton.getInstance(); Singleton test2 = Singleton.getInstance(); System.out.println(test1);//地址一样,得到的都是同一个对象 System.out.println(test2); } } //饿汉式 class Singleton { // 2.自行创建实例 private static Singleton instance = new Singleton(); // 1.构造函数私有化 private Singleton() { } public static Singleton getInstance() { return instance; } }
懒汉式:
package com.lqh.chapter03; public class _31singleton2 { public static void main(String[] args) { Singleton test1 = Singleton.getInstance(); Singleton test2 = Singleton.getInstance(); System.out.println(test1);//地址一样,得到的都是同一个对象 System.out.println(test2); } } //懒汉式 class Singleton2 { // 2.自行创建实例 private static Singleton2 instance = null; // 1.构造函数私有化 private Singleton2() { } public static Singleton2 getInstance() { if(instance == null) { instance = new Singleton2(); } return instance; } }
详细内容:
https://www.runoob.com/design-pattern/singleton-pattern.html