保证一个类只有一个对象,并提供一个访问它的全局访问点
package com.yl.demo.design;
//饿汉模式
public class SingleTon1 {
private SingleTon1(){}
private static SingleTon1 singleTon1 = new SingleTon1();
public static SingleTon1 getInstance(){
return singleTon1;
}
}
package com.yl.demo.design;
//懒汉模式
public class SingleTon2 {
private SingleTon2(){}
public static SingleTon2 singleTon2 = null;
public static SingleTon2 getInstance(){
if (singleTon2 == null) {
singleTon2 = new SingleTon2();
}
return singleTon2;
}
}
package com.yl.demo.design;
//线程安全的懒汉模式
public class SafeSingleTon {
private SafeSingleTon(){}
private static SafeSingleTon safeSingleTon = null;
public static SafeSingleTon getInstance(){
if (safeSingleTon == null) {
synchronized(SafeSingleTon.class) {
safeSingleTon = new SafeSingleTon();
}
}
return safeSingleTon;
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_41359273/article/details/123318807
内容来源于网络,如有侵权,请联系作者删除!