10.4 单例设计模式

本文介绍了设计模式中的单例模式,通过两个Java实例展示了饿汉式和懒汉式的实现方式,强调了单例模式确保类只有一个实例并提供全局访问点的核心特性。在饿汉式中,对象在类加载时即被创建,而在懒汉式中,对象在首次调用getInstance方法时创建。两种方式各有优缺点,适用于不同场景。
摘要由CSDN通过智能技术生成

10.4.1 什么是设计模式

10.4.2 什么是单例模式

10.4.3 单例模式应用实例 

public class SingleTon01 {
public static void main(String[] args) { 
// GirlFriend xh = new GirlFriend("小红"); 
// GirlFriend xb = new GirlFriend("小白"); 
//通过方法可以获取对象 
GirlFriend instance = GirlFriend.getInstance(); 
System.out.println(instance); 
GirlFriend instance2 = GirlFriend.getInstance(); 
System.out.println(instance2); 
System.out.println(instance == instance2);//T 
//System.out.println(GirlFriend.n1); 
//... 
} 
}
//有一个类, 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) { 
System.out.println("構造器被調用."); 
this.name = name; 
}
public static GirlFriend getInstance() { 
return gf; 
}
@Override 
public String toString() { 
return "GirlFriend{" + "name='" + name + '\'' + '}'; 
}
}

public class SingleTon02 { 
public static void main(String[] args) { 
//new Cat("大黃"); 
//System.out.println(Cat.n1); 
Cat instance = Cat.getInstance(); 
System.out.println(instance); 
//再次調用 getInstance 
Cat instance2 = Cat.getInstance(); 
System.out.println(instance2); 
System.out.println(instance == instance2);//T 
} 
}
//希望在程序運行過程中,只能創建一個 Cat 對象
//使用單例模式 
class Cat { 
private String name; 
public static int n1 = 999; 
private static Cat cat ; //默認是 null 
//步驟 
//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 + '\'' + '}'; 
} 
}

10.4.4 饿汉式 VS 懒汉式

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值