1.什么是单例模式?实现的思路?
![](https://img-blog.csdnimg.cn/b7e5de0c6dbb4f5f87733cd52410d636.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBARGlvbnlzdXNfeHU=,size_20,color_FFFFFF,t_70,g_se,x_16)
2.具体实现
2.1饿汉式实现
/*
*
* 单例模式1:饿汉式
*/
public class Singleton1 {
public static void main(String[] args) {
Test1 t1 = Test1.getTest1();
Test1 t2 = Test1.getTest1();
System.out.println(t1 == t2);
}
}
class Test1{
//1.私有化构造器
private Test1() {
}
//2.在类内部创建类对象
//4.把创建的对象也设置为静态的
private static Test1 test1 = new Test1();
//3.返回类对象,
//由于构造器私有,没办法在外部调用返回方法,故要求其为静态,随类的加载而加载
public static Test1 getTest1() {
return test1;
}
}
2.2懒汉式实现
/*
*
* 单利设计模式
* 2.懒汉式
*/
public class Singleton2 {
public static void main(String[] args) {
Test2 t1 = Test2.getTest2();
Test2 t2 = Test2.getTest2();
System.out.println(t1 == t2);
}
}
class Test2{
//1.私有化构造器
private Test2() {
}
//2.在类内部创建类的对象
//4.设置类对象为静态
// 由于对象中要调用test2 所以test2也需要定义为static的
private static Test2 test2 = null;
//3.返回设置的对象
//由于外部无法创建类的对象,
// 调用getTest2()方法,所以要求其为静态方法,随类的加载而加载
public static Test2 getTest2() {
if(test2 == null)
test2 = new Test2();
return test2;
}
}