单例设计模式(两种)
饿汉式
- 可能造成创建了对象但是没有使用(弊端)
- 没有去使用就创建实例
- 随着类的加载而创建
package com.xz.single_;
public class SingleTon01 {
public static void main(String[] args) {
GirlFriend instance1 = GirlFriend.getInstance();
System.out.println(instance1);
//GirlFriend类只会被加载一次,所以即使再创建,都是同一个对象
GirlFriend instance2 = GirlFriend.getInstance();
System.out.println(instance2);
//验证
System.out.println(instance1 == instance2);//true
//System.out.println(BoyFriend.getInstance());
}
}
class GirlFriend {
private String name;
//为了能够在静态方法中, 返回 gf 对象,需要将其修饰为static
private static GirlFriend gf = new GirlFriend("小红");
//如何保证我们只能创建一个 GirlFriend 对象
//步骤
//1.将构造器私有化
//2.在类的内部直接创建
//3.提供一个公共的static方法, 返回 gf 对象
private GirlFriend(String name) {
this.name = name;
}
public static GirlFriend getInstance() {
return gf;
}
@Override
public String toString() {
return "GirlFriend{" +
"name='" + name + '\'' +
'}';
}
}
class BoyFriend {
private String name;
private static BoyFriend bf = new BoyFriend("小帅");
private BoyFriend(String name) {
this.name = name;
}
public static BoyFriend getInstance() {
return bf;
}
@Override
public String toString() {
return "BoyFriend{" +
"name='" + name + '\'' +
'}';
}
}
懒汉式
-
演示懒汉式的单例模式
-
程序在运行中,只能创建一个对象
-
不会随着类的加载创建对象
-
只有当用户使用getInstance()时,才返回对象,后面再次调用是,会返回上次创建的对象
步骤
- 构造器私有化
- 定义一个static静态属性对象
- 提供一个public的static方法,可以返回一个对象
package com.xz.single_;
public class SingleTon02 {
public static void main(String[] args) {
Cat instance1 = Cat.getInstance();
System.out.println(instance1);
Cat instance2 = Cat.getInstance();
System.out.println(instance2);
System.out.println(instance1 == instance2);
}
}
class Cat {
private String name;
private static Cat cat;
private Cat(String name) {
this.name = name;
}
public static Cat getInstance() {
if (cat == null) {
cat = new Cat("小可爱");
}
return cat;
}
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
'}';
}
}