您的位置:首页 > 其它

单例模式

2018-03-20 10:28 95 查看
单例模式也就是指的是一个类只能有一个实例对象,不需要用户创建,由他本身自己创建,给用户提供方法进行获取。

1、构造方法私有,用户无法创建。

2、类中有一个该类静态私有对象

3、为用户提供方法获取这个对象

1、懒汉式,线程不安全

静态对象为null,需要时进行判断,然后创建

/**
* 懒汉式。线程不安全
* */
public class Singleton {
private static Singleton instance;

private Singleton() {
}

public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}


2、懒汉式,线程安全

/**
* 懒汉式。线程安全
* 若多个线程同时执行get方法,同时进行if判断,则判断成功,创建多个对象,线程不安全
* */
public class Singleton {
private static Singleton instance;

private Singleton() {
}

public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}


3、饿汉式,线程安全

静态对象直接创建

/**
* 饿汉式。线程安全
* */
public class Singleton {
private static Singleton instance = new Singleton();

private Singleton() {
}

public static  Singleton getInstance(){
return instance;
}
}


4、双检锁,线程安全

避免了每次线程同步所花费的时间,提高了效率,只在第一次时进行线程同步,创建对象

/**
* 双重锁。线程安全
* */
public class Singleton {
private volatile static Singleton instance;

private Singleton() {
}

public static  Singleton getInstance(){
if(instance == null){
synchronized (Singleton.class) {
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}


为什么要加volatile关键字

https://www.cnblogs.com/doit8791/p/5308724.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息