单例设计模式
1、单例设计模式:单:一个,单个;例:实例,在某些情况下,设计一个类,这个类有且仅有一个对象
2、单例设计原则
(1)构造方法私有化
(2)在类中创建好对象
(3)在类中对外提供获取对象的方法
3、思路
可以理解为成员变量私有化,对外提供了set、get方法
(一)饿汉式
1、在加载类的时候,就要初始化静态成员变量,所以就同时将本类的对象创建出来
2、饿汉式:一给食物就吃,类一加载就要去创建对象
public class Demo01_TheHungryType {
public static void main(String[] args) {
TheHungryType th1 = TheHungryType.getTht();
TheHungryType th2 = TheHungryType.getTht();
System.out.println(th1 == th2);
System.out.println(th1);
System.out.println(th2);
}
}
/**
* (1)构造方法私有化
* (2)在类中创建好对象
* (3)在类中对外提供获取对象的方法
*/
class TheHungryType {
//1、构造方法私有化
private TheHungryType() {
}
//2、在类中创建好对象
private static TheHungryType tht = new TheHungryType();
//3、在类中对外提供获取对象的方法
public static TheHungryType getTht() {
return tht;
}
}
(二)饿汉式二
1、懒汉式:在加载类的时候不着急创建对象,等到调用方法经过好几层判断之后,非得创建不可才去创建,就像懒汉,我能不做就不做
2、懒汉式在面试中也是重点提问的对象
public class Demo03_TheHungryTypeTwo {
public static void main(String[] args) {
TheHungryTypeTwo th1 = TheHungryTypeTwo.th;
TheHungryTypeTwo th2 = TheHungryTypeTwo.th;
System.out.println(th1 == th2);
System.out.println(th1);
System.out.println(th2);
}
}
/**
* (1)构造方法私有化
* (2)在类中创建好对象
* (3)在类中对外提供获取对象的方法
*/
class TheHungryTypeTwo {
//1、构造方法私有化
private TheHungryTypeTwo(){}
//2、提前在类中创建好对象
public static final TheHungryTypeTwo th = new TheHungryTypeTwo();
}
(三)懒汉式
public class Demo02_LazyMan {
public static void main(String[] args) {
LazyMan lm1 = LazyMan.getInstance();
LazyMan lm2 = LazyMan.getInstance();
System.out.println(lm1 == lm2);
}
}
class LazyMan {
//1、构造方法私有化
private LazyMan() {
}
//2、在类中创建好对象
private static LazyMan lm;
//3、对外提供公开的访问方式
public static LazyMan getInstance() {
//内外层判断一个都不能少,外层主要提高效率,但是如果将内层if去掉,会重新出现线程安全问题
//3、多线程环境下如果每一次都获取同步锁对象再去判断效率较低,外层加上一个判断,能尽可能的提高效率
if (lm == null) {
//2、多线程的环境下,无法保证线程的安全,所以加上同步锁对象保证操作的完整性
synchronized (LazyMan.class) {
//1、判断当前对象是否为空,如果存在就不创建,不存在就创建
if (lm == null) {
lm = new LazyMan();
}
}
}
return lm;
}
}
版权声明:本文为xxxx1982原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。