废话不多说直接上代码,文末有整理
import java.util.concurrent.locks.Lock;
public class Main {
public static void main(String[] args) {
System.out.println("单例模式学习!");
System.out.println("懒汉式单例");
Person person = Person.instance();
//优点节省内存,缺点多线程情况下会产生多个实例[出现的情况为多个线程同时执行到if (person == null),同时执行return new Person();会导致创建多个Person对象]
System.out.println("饿汉式单例");
Student student = Student.instance();
//优点简单易懂,线程安全。缺点浪费内存。
System.out.println("双重加锁单例");
Child child = Child.instance();
//最常用的形式,但是因为JVM的关系首次创建浪费时间,并且存在创建失败的可能[概率很低很低],单依旧不影响他的使用频率
}
}
class Person{
private String username;
private String sex;
private String address;
private static Person person = null;
public static Person instance(){
if (person == null){
return new Person();
}else{
return person;
}
}
}
class Student{
private String username;
private String sex;
private String address;
private static Student student = new Student();
public static Student instance(){
return student;
}
}
class Child{
private String username;
private String sex;
private String address;
private static Child child = null;
private static final Object a = new Object();
public static Child instance(){
if (child == null){
synchronized (a){
if (child == null) return new Child();
}
}
return child;
}
}
总结:
太简单了,不解释。
除上述三种方法之外还存在,枚举单例、静态内部类单例等写法,不过使用并不普遍,暂不考虑。
参考资料:单例模式的六种写法