Dowemo
0 0 0 0

Lazy

//懒汉式publicclass Singleton {
 //作用:无法被外部实例化。privateSingleton() {
 };
 //静态有个重要的特点。一个类只有一个privatestatic Singleton single = null;
 //静态工厂方法:产生本类对象publicstatic Singleton getInstance() {
 if (single == null) {
 single = new Singleton();
 }
 return single;
 }
}

//饿汉式publicclass Singleton1 {
 privateSingleton1() {
 };
 //不管有没有。先new一个privatestatic Singleton1 single = new Singleton1();
 publicstatic Singleton1 getInstance() {
 return single;
 }
}

Complete design

//完整的饿汉式设计:使用了双重检测机制实现线程安全的饿汉式publicclass Singlentonsyn {
 privatestaticvolatile Singlentonsyn instance = null;
 privateSinglentonsyn() {
 }
 publicstatic Singlentonsyn getInstance() {
 if (instance == null) {
 synchronized (Singlentonsyn.class) {
 if (instance == null) {
 instance = new Singlentonsyn();
 }
 }
 }
 return instance;
 }
}

Static internal classes implement singleton mode

//静态内部类实现线程安全的单例模式publicclass SingletonHand {
 privateSingletonHand() {
 }
 privatestaticclass SingletonHandHandler {
 privatestatic SingletonHand instance = new SingletonHand();
 }
 publicstatic SingletonHand getInstance() {
 return SingletonHandHandler.instance;
 }
}



Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs