懒汉模式

如何确保我们只能创建一个 GirlFriend 对象

  1. 将构造器私有化
  2. 在类的内部直接创建
  3. 提供一个公共的static方法,返回 gf 对象.
  1. public class SingleTon01 {
  2. public static void main(String[] args) {
  3. // GirlFriend xh = new GirlFriend("小红");
  4. // GirlFriend xb = new GirlFriend("小白");
  5. //通过方法可以获取对象
  6. GirlFriend instance = GirlFriend.getInstance();
  7. System.out.println(instance);
  8. GirlFriend instance2 = GirlFriend.getInstance();
  9. System.out.println(instance2);
  10. System.out.println(instance == instance2);//T
  11. //System.out.println(GirlFriend.n1);
  12. //...
  13. }
  14. }
  1. //有一个类, GirlFriend
  2. //只能有一个女朋友
  3. class GirlFriend {
  4. private String name;
  5. //public static int n1 = 100;
  6. //为了能够在静态方法中,返回 gf对象,需要将其修饰为static
  7. //對象,通常是重量級的對象, 餓漢式可能造成創建了對象,但是沒有使用.
  8. private static GirlFriend gf = new GirlFriend("小红红");
  9. //如何保障我们只能创建一个 GirlFriend 对象
  10. //步骤[单例模式-饿汉式]
  11. //1. 将构造器私有化
  12. //2. 在类的内部直接创建对象(该对象是static)
  13. //3. 提供一个公共的static方法,返回 gf对象
  14. private GirlFriend(String name) {
  15. System.out.println("構造器被調用.");
  16. this.name = name;
  17. }
  18. public static GirlFriend getInstance() {
  19. return gf;
  20. }
  21. @Override
  22. public String toString() {
  23. return "GirlFriend{" +
  24. "name='" + name + '\'' +
  25. '}';
  26. }
  27. }

懒汉模式

  1. 仍然构造器私有化
  2. 定义一个static静态属性对象
  3. 提供一个public的static方法,可以返回一个Car对象.
  4. 懒汉式:只有当用户使用getInstance时,才返回cat对象,后面再次调用时,会返回上一次创建的cat对象
  1. //希望在程序運行過程中,只能創建一個Cat對象
  2. //使用單例模式
  3. class Cat {
  4. private String name;
  5. public static int n1 = 999;
  6. private static Cat cat ; //默認是null
  7. //步驟
  8. //1.仍然構造器私有化
  9. //2.定義一個static靜態屬性對象
  10. //3.提供一個public的static方法,可以返回一個Cat對象
  11. //4.懶漢式,只有當用戶使用getInstance時,才返回cat對象, 後面再次調用時,會返回上次創建的cat對象
  12. // 從而保證了單例
  13. private Cat(String name) {
  14. System.out.println("構造器調用...");
  15. this.name = name;
  16. }
  17. public static Cat getInstance() {
  18. if(cat == null) {//如果還沒有創建cat對象
  19. cat = new Cat("小可愛");
  20. }
  21. return cat;
  22. }
  23. @Override
  24. public String toString() {
  25. return "Cat{" +
  26. "name='" + name + '\'' +
  27. '}';
  28. }
  29. }

小结:

  1. 单例模式的两种实现方式 (1) 饿汉式 (2) 懒汉式
  2. 饿汉式的问题: 在类加载时就创建,可能存在资源浪费问题
  3. 懒汉式的问题: 线程安全问题,后续会完善