单例模式的理解
Posted Blue_Keroro
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单例模式的理解相关的知识,希望对你有一定的参考价值。
参考:https://blog.csdn.net/yanbober/article/details/45312675
模式:根据实例化对象时机不同分为懒汉模式与饿汉模式
饿汉模式是单例类被加载时候就实例化一个对象交给自己的引用;懒汉模式时在调用取得实例方法的时候才会实例化对象。
1 package yanbober.github.io; 2 //饿汉模式 3 class DBManager { 4 private static DBManager mInstance = new DBManager(); 5 6 private DBManager() {} 7 8 public static DBManager getInstance() { 9 return mInstance; 10 } 11 12 public boolean update() { 13 System.out.println("update dbase success!"); 14 return true; 15 } 16 } 17 18 public class Main { 19 public static void main(String[] args) { 20 DBManager dbManager = DBManager.getInstance(); 21 dbManager.update(); 22 } 23 }
package yanbober.github.io;
//懒汉模式(线程安全高并发低性能)
class DBManager {
privatestatic DBManager mInstance;
privateDBManager() {}
publicstaticsynchronized DBManager getInstance() {
if (null == mInstance) {
mInstance = new DBManager();
}
return mInstance;
}
publicbooleanupdate() {
System.out.println("update dbase success!");
returntrue;
}
}
publicclass Main {publicstaticvoidmain(String[] args) {
DBManager dbManager = DBManager.getInstance();
dbManager.update();
}
}
1 package yanbober.github.io; 2 //懒汉模式(相对比较靠谱模式) 3 class DBManager { 4 private static volatile DBManager mInstance; 5 6 private DBManager() {} 7 8 public static DBManager getInstance() { 9 if (null == mInstance) { 10 synchronized(DBManager.class) { 11 if (null == mInstance) { 12 mInstance = new DBManager(); 13 } 14 } 15 } 16 return mInstance; 17 } 18 19 public boolean update() { 20 System.out.println("update dbase success!"); 21 return true; 22 } 23 } 24 25 public class Main { 26 public static void main(String[] args) { 27 DBManager dbManager = DBManager.getInstance(); 28 dbManager.update(); 29 } 30 }
//饿汉模式 class DBManager { privatestatic DBManager mInstance = new DBManager(); privateDBManager() {} publicstatic DBManager getInstance() { return mInstance; } publicbooleanupdate() { System.out.println("update dbase success!"); returntrue; } } publicclass Main {publicstaticvoidmain(String[] args) { DBManager dbManager = DBManager.getInstance(); dbManager.update(); } }
以上是关于单例模式的理解的主要内容,如果未能解决你的问题,请参考以下文章