懒汉模式,饿汉模式

懒汉模式:调用方法是才new对象

线程安全问题,加上synchronized修饰

  1. Public class Singleton{
  2.          Private static Singleton instance;
  3.          Private Singleton(){};
  4.          Public static synchronized Singleton getinstance(){
  5.                    If(null==instance){
  6.                             Instance = new Singleton():
  7.                    }
  8. Return instance;
  9.          }
  10. }

饿汉模式:直接new对象

这种方式基于classloder机制避免了多线程的同步问题

  1. Public class Singleton{
  2.          Private static Singleton instance = new Singleton();
  3.     Private Singleton();
  4.          Public static Singleton getinstance(){
  5.                    Return instance;
  6.          }
  7. }
posted @ 2017-04-16 15:20  Jemb  阅读(46)  评论(0)    收藏  举报