1、是不是号称恶汉,就是类加载就初始化了
- package com.zhy.pattern.singlton;
- public class Singleton
- {
- private static Singleton instance = new Singleton();
- public static Singleton getInstance()
- {
- return instance ;
- }
- }
2、懒汉,我喜欢这种,需要双重判断
- package com.zhy.pattern.singlton;
- public class Singleton02
- {
- private static Singleton02 instance;
- public static Singleton02 getInstance()
- {
- if (instance == null)
- {
- synchronized (Singleton02.class)
- {
- if (instance == null)
- {
- instance = new Singleton02();
- }
- }
- }
- return instance;
- }
- }
3、使用Java的枚举,还是很推荐的,简单的跟神马一样,如果对枚举不熟悉,小google一下
- public enum Singleton03
- {
- INSTANCE;
- }
- package com.zhy.pattern.singlton;
- public class Singleton04
- {
- private static final class InstanceHolder
- {
- private static Singleton04 INSTANCE = new Singleton04();
- }
- public static Singleton04 getInstance()
- {
- return InstanceHolder.INSTANCE;
- }
- }
好了,就这么多,以上4种都是比较推荐使用的,除了第一种会类加载的时候初始化,其他3种都不会,且4种都保证线程安全,特殊情况(除了多个类加载器,和你非要通过反射等手段生成多个对象)不考虑。