单例模式

来源:互联网 发布:中国进出口数据分析 编辑:程序博客网 时间:2024/06/17 19:48
单例模式:         
        单例对象是一种常见的设计模式。在java中,单例对象能保证在一个JVM中,该对象只有一个实例存在。这样的模式有几个好处:
        1,某些类创建比较频繁,对于一些大型的对象,这是一笔很大的系统开销
        2,省去了new操作,降低了系统内存的使用频率,减轻了GC压力
        3,有些类如交易所的核心交易引擎,控制着交易流程,如果该类可以创建多个的话,系统完全乱了,所以只有使用单例模式,才能保证核心交易服务器独立
的控制整个流程。
        一个简单的单例类:
        public class Singleton{                private static Singleton instance=null;                private Singleton(){                }                public static Singleton getInstance(){                        if(instance==null){                                instance=new Singleton();                        }                        return instance;                }        }
        这个类可以满足基本需求但是,毫无线程安全保护的类,如果放入多线程环境下,肯定会引发问题,如何解决?对getInstance方法添加synchronzed关键字>。
        public static synchronzed getInstance(){                if(instance==null){                        instance=new Singleton();                }                return instance;        }
        饿汉式单例模式:
        public static synchronzed getInstance(){                if(instance==null){                        instance=new Singleton();                }                return instance;        }

       懒汉式单例模式:
 
               public class Singleton{                        private static Singleton instance=null;                        private Singleton(){}                        public static Singleton isntance(){                                if(instance==null){                                        instance=new Singleton();                                }                                return instance;                        }                }
        登记式单例类:
 
       import java.util.HashMap;        import java.util.Map;        public class Singleton3{                private static Map<String,Singleton3>=new HashMap<String,Singleton3>                static{                        Singleton3 single=new Singleton3();                        map.put(single.getClass().getName(),single);                }                private Singleton3(){}                public static Singleton getInstance(String name){                        if(name==null){                                name=Singleton3.class.getName();                        }                        if(map.get(name)==null){                                try{                                        map.put(name,(Singleton3)Class.forName(name).newInstance());                                }catch(InstantitionException e){                                        e.printStackTrace();                                }catch(IllegalAccessException e){                                        e.printStackTrace();                                }catch(ClassNotFoundException e){                                        e.printStackTrace();                                }                        }                        return map.get(name);                }        }


0 0
原创粉丝点击