什么是单例模式
单例(单个的实例)
1、所谓的单例设计模式,就说采取一定的方法保证在整个的软件系统中,对某个只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法
2、单例模式只有两种方式:1)饿汉式 2)懒汉式
饿汉式(在类被调用的时候就创建了)
/**
* 饿汉式-单例设计模式
*/
public class SingleTon01 {
public static void main(String[] args) {
// GirlFriend girlFriend1 = new GirlFriend("小红");
// GirlFriend girlFriend2 = new GirlFriend("小兰");
//通过方法可以直接获取对象
GirlFriend instance = GirlFriend.girlFriend();
System.out.println(instance);
GirlFriend instance2 = GirlFriend.girlFriend();
System.out.println(instance2);
System.out.println(instance == instance2);
}
}
//有一个类, GirlFriend
//只能有一个女朋友
class GirlFriend {
private String name;
public static int n1 =100;
//为了能够在静态方法中, 返回 gf 对象,需要将其修饰为 static
//因为在类的调用,便会加载创建。
//对象,通常是重量级的对象,饿汉式可能造成创建了对象,但是没有使用
private static GirlFriend gf = new GirlFriend("小红");
//如何保证我们只能创建一个 GirlFriend
//步骤[单例模式-饿汉式]
//1. 将构造器私有化
//2. 在类的内部直接创建对象(该对象是static)
//3. 提供一个公共的static方法,返回 gf 对象
private GirlFriend(String name) {
this.name = name;
}
public static GirlFriend girlFriend() {
return gf;
}
@Override
public String toString() {
return "GirlFriend{" +
"name='" + name + '\'' +
'}';
}
}
懒汉式:
/**
* 懒汉式的单例模式
*/
public class SingleTon02 {
public static void main(String[] args) {
System.out.println(Cat.n1);
Cat instance = Cat.getInstance();
System.out.println(instance);
//再次调用
Cat instance2 = Cat.getInstance();
System.out.println(instance2);
System.out.println(instance == instance2);
}
}
//希望在程序运行过程中,只能创建一只Cat对象
class Cat {
private String name;
public static int n1 = 999;
private static Cat cat;//默认为空
//步骤
//1.仍然构造器私有化
//2.定义一个static静态属性对象
//3.提供一个公共的public的static方法,可以返回一只Cat对象
//4.懒汉式,只有当用户使用getInstance时,才返回Cat对象,对象再次调用时,会返回上次创建的Cat对象
//从而保证了单例
private Cat(String name) {
System.out.println("构造器调用...");
this.name = name;
}
public static Cat getInstance() {
if (cat == null) {//如果没有创建Cat对象
cat = new Cat("小可爱");
}
return cat;
}
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
'}';
}
}
饿汉式VS懒汉式
1、二者主要的区别在于创建对象的时机不同:饿汉式是在类加载就创建了对象实例,而懒汉式是在使用时才创建。
2、饿汉式不存在线程安全问题,懒汉式存在线程安全问题,
3、饿汉式存在浪费资源的可能。因为如果程序员一个对象那个实例都没有使用,那么饿汉式创建的对象就浪费了,懒汉式是使用时才创建,就不存在这个问题。
小结:
①单例模式的两种实现方式(1)饿汉式(2)懒汉式
②饿汉式的问题:在类加载时就创建,可能存在资源浪费问题。
③懒汉式的问题:存在线程安全问题。