//20210117
写在前面:刚期末考试完,考了面向对象,里边儿有23个设计模式,我寻思着考完挨个儿实现一下,本文实现单例模式
单例模式概念:
- 私有化构造器,让一个类只能拥有一个实例化对象,并创建静态方法用以获取该对象
饿汉式
- 无论是否调用,都先自己创建对象
- 源代码如下:
/**
* hunger man mode
*/
public class HungerSingleton {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private static volatile HungerSingleton hungerSingleton;
private HungerSingleton(){}
public static HungerSingleton newInstance(){
return hungerSingleton;
}
}
懒汉式
- 只有在请求的时候才创建对象
- 程序源代码如下:
/**
* lazy man mode
*/
public class LazySingleton {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private static volatile LazySingleton lazySingleton;
private LazySingleton(){}
public static LazySingleton newInstance(){
if(lazySingleton==null){
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
}
双重加锁式
- 该模式是饿汉式的线程安全版
- 程序源代码如下:
public class Singleton_Double_Check {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private static volatile Singleton_Double_Check singletonDoubleCheck;
private final static Object lock_ = new Object();
//私有化构造器
private Singleton_Double_Check(){
}
public static Singleton_Double_Check newInstance(){
if(singletonDoubleCheck ==null){
synchronized (lock_){
if(singletonDoubleCheck ==null){
singletonDoubleCheck = new Singleton_Double_Check();
}
return singletonDoubleCheck;
}
}
return singletonDoubleCheck;
}
}
以上
希望对大家有所帮助