我的博客园:https://www.cnblogs.com/djhzzl/p/14378952.html
单例模式
单例(Singleton)模式是设计模式之一,最显著的特点就是一个类在一个JVM中只有一个实例,避免繁琐的创建销毁实例。
简单例子
先看简单的单例模式实现完整代码:
Singleton_Test类使用单例模式 ,采用饿汉式方法。
public class Singleton_Test {
private Singleton_Test() {
System.out.println("私有化构造方法");
}
//饿汉式
private static Singleton_Test Instance = new Singleton_Test();
public static Singleton_Test getInstance() {
return Instance;
}
}
再编写一个测试类Main
public class Main {
public static void main(String args[]) {
Singleton_Test test1 = Singleton_Test.getInstance();
Singleton_Test test2 = Singleton_Test.getInstance();
System.out.println(test1 == test2);
/**
运行结果:
私有化构造方法
true
*/
}
}
逐步分析
1.构造方法私有化
首先,实现单例模式的类,构造方法私有化(private),外部无法实例化(new)该类。
public class Singleton_Test {
private Singleton_Test(){
System.out.println("私有化构造方法");
}
}
无法实例化 Singleton_Test 类。
2.私有静态类属性指向实例
所以需要提供一个public static 方法 getInstance(),外部通过这个方法获取对象,并且由于是 实例化的同一个类,所以外部每次调用都是调用同一个方法,从而实现一个类只有一个实例。
private static Singleton_Test Instance = new Singleton_Test();
//饿汉式
private static Singleton_Test Instance ;
//懒汉式
3.使用公有静态方法返回实例
返回的都是同一个类,保证只实例化唯一一个类
public static Singleton_Test getInstance(){
return Instance;
}
4.测试类
public static void main(String args[]) {
Singleton_Test test1 = Singleton_Test.getInstance();
Singleton_Test test2 = Singleton_Test.getInstance();
System.out.println(test1 == test2);
/**
运行结果:
私有化构造方法
true
*/
}
输出结果表示,实例化的是同一个类,并只调用一次构造方法。
单例模式的实现
饿汉式
这种方式无论是否调用,加载时都会创建一个实例。
private static Singleton_Test Instance = new Singleton_Test();
public static Singleton_Test getInstance(){
return Instance;
}
懒汉式
这种方式,是暂时不实例化,在第一次调用发现为null没有指向时,再实例化一个对象。
private static Singleton_Test Instance ;
public static Singleton_Test getInstance(){
if (Instance == null){
Instance = new Singleton_Test();
}
return Instance;
}
区别
-
饿汉式的话是声明并创建对象(他饿),懒汉式的话只是声明对象(他懒),在调用该类的 getInstance() 方法时才会进行 new对象。
-
饿汉式立即加载,会浪费内存,懒汉式延迟加载,需要考虑线程安全问题 什么是线程安全/不安全
-
饿汉式基于 classloader 机制,天生实现线程安全,懒汉式是线程不安全。需要加锁 (synchronized)校验等保证单例,会影响效率
总结
-
构造方法私有化
private Singleton_Test(){} -
私有静态(static)类属性指向实例
private static Singleton_Test Instance -
使用公有静态方法返回实例
public static Singleton_Test getInstance(){ return Instance;}