所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例。
饿汉式:
class Bank{
//1.私化类的构造器
private Bank(){
}
//2.内部创建类的对象
//4.要求此对象也必须声明为静态的
private static Bank instance = new Bank();
//3.提供公共的静态的方法,返回类的对象
public static Bank getInstance(){
return instance;
}
}
//使用同步机制将单例模式中的懒汉式改写为线程安全的
public class SafeOfThread {
// 私有化构造器
private SafeOfThread() {
}
// 定义同步监视器
static Object object = new Object();
// 定义单例对象并赋值为null
private static SafeOfThread instance = null;
// 定义方法给单例对象初始化,并返回单例对象----同步代码块
public static SafeOfThread getInstance() {
synchronized (object) {
if (instance == null) {
instance = new SafeOfThread();
}
return instance;
}
}
// 优化效率
// public static SafeOfThread getInstance() {
// if (instance == null){
// synchronized (object) {
// if (instance == null) {
// instance = new SafeOfThread();
// }
// }
// }
// return instance;
// }
// 使用同步方法保证线程安全
// public static synchronized SafeOfThread getInstance() {
// if (instance == null) {
// instance = new SafeOfThread();
// }
// return instance;
// }
}