- /**
- * 饿汉式
- * @author Administrator
- *
- */
- class EagerSingleton {
- private static EagerSingleton instance = new EagerSingleton();
- private EagerSingleton(){}
-
- public EagerSingleton getInstance(){
- return instance;
- }
- }
- /**
- * 线程不安全的饱汉式
- */
- class LazySingleton{
- private static LazySingleton instance;
- private LazySingleton(){}
- public LazySingleton getInstance(){
- if(instance == null){
- instance = new LazySingleton();
- }
- return instance;
- }
- }
- /**
- * 线程安全的饱汉式
- * 即双重锁判定模式
- */
-
- class LockSingleton{
- private static LockSingleton instance;
- private LockSingleton(){}
- public LockSingleton getInstance(){
- if (instance == null) {
- synchronized (LockSingleton.class) {
- if (instance == null) {
- instance = new LockSingleton();
- }
- }
- }
- return instance;
- }
- }
- /**
- * 线程安全的单例模式二
- */
- class SafeSingleton{
- private static SafeSingleton instance;
- private SafeSingleton(){}
- public synchronized SafeSingleton getInstance(){
- if(instance == null){
- instance = new SafeSingleton();
- }
- return instance;
- }
- }
-
- /**
- * 只有一个枚举值的枚举也可以用作单例模式
- */
- enum EnumSingleton{
- INSTANCE {
- @Override
- protected void someMethod() {
- // TODO Auto-generated method stub
- //需要实现的代码
- }
- };
-
- protected abstract void someMethod();
- }
复制代码 |