单例模式

1. 单例模式的两种实现方式:
a) 饿汉式
public class ClientManager {
private static ClientManager instance = new ClientManager();

private ClientManager () {
}

public static ClientManager getInstance() {
return instance;
}
}

b) 懒汉式(需要注意同步)
public class UserManager {
private static UserManager instance = null;

private UserManager() {
}

public static synchronized UserManager getInstance() {
if(instance == null) {
instance = new UserManager();
}
return instance;
}
}


2. 了解单例模式的三要素
a) 私有的静态的成员变量
b) 私有的构造方法
c) 公共的静态的入口点方法

3. 单例模式的要点有三个
a) 一是某个类只能有一个实例;
b) 二是它必须自行创建这个实例;
c) 三是它必须自行向整个系统提供这个实例。

4. 单例模式的应用场景:类中没有可以修改的成员变量(这个类没有状态),如果存在可以修改的成员变量,将会产生线程安全问题,不建议使用。一些资源管理器(或管理类)常常设计成单例模式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值