static只是在程序加载的时候分配内存,有没有保证同步?
singleton模式保证只有一个实例,但是有没有什么不好的地方?有没有坚决不能用singgleton而必须用static声明一个方法。
------解决方案--------------------
------解决方案--------------------
当然不是!
首先:Singleton是对象,而用static修饰class的时候是方法集合!
其次上述的差别也很大:
第一:Singleton是对象,static 是方法;
第二:Singleton可以进行继承或接口实现,
第三:Singleton可以保持状态,可以延迟加载,可以序列化
第四:Singleton可以状态化,这样多个单态类在一起就可以作为一个状态仓库一样向外提供服;
另外:应用如果基于容器,则应该尽量少用或者不用Singleton!
------解决方案--------------------
- Java code
public class Singleton { private static Singleton s = null; private Singleton() { } public static Singleton getInstance() { if (s == null) s = new Singleton(); return s; } public void fun() { /* some code */ } public static void staticfun() { /* some code */ } public static void main(String[] args) { Singleton.getInstance().fun(); Singleton.staticfun(); }}
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------