`

单例模式例子

 
阅读更多

=============如下是一个单例例子===================

public class M8AccountsSingleton {
 private static final M8AccountsSingleton accountsSingleton ;
 private static Map<String, String> m8AccountsMap = new HashMap<String, String>();
 
 static{
  accountsSingleton = new M8AccountsSingleton();
 }
 
 public static M8AccountsSingleton getInstance() {
  return accountsSingleton;
 }
 
 private M8AccountsSingleton (){
  init();
 }
 
 private void init() {
  try {
   m8AccountsMap.clear();
   m8AccountsMap.putAll(ServiceFactory.getInstance().getPaymentListService().getM8AccountsMap(JdbcUtils.getM8Accounts()));
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 /**
  * 外部调用此方法用于刷新缓存
  */
 public synchronized void refreshCache() {
  init();
 }
 
 public Map<String, String> getM8AccountsMap() {
  return this.m8AccountsMap;
 }
}

 

=============如下是一个线程,刷新缓存===================

public class M8AccountsSingletonThread implements Runnable {
 private final Logger log = Logger.getLogger(M8AccountsSingletonThread.class);

 public void run() {
  try {
   // 刷新m8单位信息
   M8AccountsSingleton.getInstance().refreshCache();
  } catch (Exception e) {
   log.error("刷新获取m8单位信息单例异常:", e);
  }
 }
}

 

=============系统启动初始化M8单位信息===================

  M8AccountsSingleton.getInstance().refreshCache();

分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

Global site tag (gtag.js) - Google Analytics