class Singleton{ //使用private防止new private Singleton(){ } //类的内部建立对象 private final static Singleton instance = new Singleton(); //向外暴露一个静态的公共方法 public static Singleton getInstance(){ return instance; } }
优缺点:java
优势 | 写法简单,在类装载的时候完成实例化,避免了线程同步问题 |
---|---|
缺点 | 在类装载的时候就完成实例化,没有达到lazy Loading的效果,若是一直没有用到,会形成内存的浪费 |
没法保证是本身触发的静态的方法数据库
class Singleton{ //使用private防止new private Singleton(){ } //类的内部建立对象 private static Singleton instance; static{ //在静态代码块里建立 instance = new Singleton(); } //向外暴露一个静态的公共方法 public static Singleton getInstance(){ return instance; } }
优缺点和静态常量同样设计模式
class Singleton{ //类的内部建立对象 private static Singleton instance; //使用private防止new private Singleton(){ } //使用的時候才建立出来 懒汉式 public static Singleton getInstance(){ if(instance == null){ instance = new Singleton(); } return instance; } }
优势 | 起到了lazy Loading的效果 |
---|---|
缺点 | 只能在单线程下使用,在多线程下,一个线程进入了if语句中,没来得及执行完,另外一个线程也经过了这个判断语句,这时候就会产生多个实例,因此在多线程下不能够使用和这个方式 |
class Singleton{ //类的内部建立对象 private static Singleton instance; //使用private防止new private Singleton(){ } //加入了同步代码,解决线程不安全问题 public static synchronized Singleton getInstance(){ if(instance == null){ instance = new Singleton(); } return instance; } }
优势 | 解决了线程不安全的问题 |
---|---|
缺点 | 效率很低,方法只须要执行一次就能够了,可是使用这个方法须要执行不少次,都要进行同步 |
class Singleton{ //类的内部建立对象 private static Singleton instance; //使用private防止new private Singleton(){ } public static Singleton getInstance(){ if(instance == null){ synchronized (Singleton.class){ instance = new Singleton(); } } return instance; } }
线程不安全(有人写)不能够启到线程同步的做用(==错误==)安全
class Singleton{ //volatile防止指令重排 private static volatile Singleton instance; //使用private防止new private Singleton(){ } //双重检查,解决线程安全问题,实现了懒加载的方式 public static Singleton getInstance(){ if(instance == null){ synchronized (Singleton.class){ if(instance == null){ instance = new Singleton(); } } } return instance; } }
优势 | Double-Check多线程中常常使用,保证了线程的安全,避免重复的方法同步,延迟加载,效率较高 |
---|---|
结论 | 推荐使用 |
class Singleton{ //使用private防止new private Singleton(){ } //双重检查,解决线程安全问题,实现了懒加载的方式 public static SingletonInstance{ private static final Stingleton INSTANCE = new Singleton(); } public static Singleton getInstance(){ return SingletonInstance.INSTANCE; } }
实现了线程安全,使用延迟加载(很好的一种模式),效率高session
静态内部类装载的时候是安全的多线程
enum Singleton{ INSTANCE; public void say(){ System.out.println("ok"); } }
借助JDK1.5的枚举来实现,避免多线程同步问题,还能防止反序列化从新建立新的对象app
是Josh Bloch提倡的方式工具
🌰Runtime:性能
public class Runtime { private static Runtime currentRuntime = new Runtime(); /** * Returns the runtime object associated with the current Java application. * Most of the methods of class <code>Runtime</code> are instance * methods and must be invoked with respect to the current runtime object. * * @return the <code>Runtime</code> object associated with the current * Java application. */ public static Runtime getRuntime() { return currentRuntime; } /** Don't let anyone else instantiate this class */ private Runtime() {}