饿汉式:(理解记忆:因为“饿”,想一下“吃饱”,在建立对象时即给对象赋值)
代码:
- class Single
- {
- private Single(){}
- private static Single s = new Single();
- public static Single getInstance()
- {
- return s;
- }
- }
复制代码
懒汉式:(理解记忆:因为“懒”,在建立对象时没有赋值,而是在调用对外的方法时对其赋值)
懒汉式应解决多线程问题
代码:
- class Single
- {
- private static Single s = null;
- private Single(){};
- public static Single getInstance()
- {
- if(s==null)
- {
- synchronized(Single.class)
- {
- if(s==null)
- s = new Single();
- }
- }
- return s;
- }
- }
复制代码
|
|