public class Instance { private Instance() { } // 1恶汉式 代码简单 但没有实现延迟加载,耗资源;并且线程不安全,当两条线程同时执行,会创建重复对象; // private static Instance instance=new Instance(); // public static Instance getInstance(){ // return instance; // } // 2懒汉式 代码简单 实现的延迟加载,但线程不安全,多线程时无法正常工作; // private static Instance instance=null; // public static Instance getInstance(){ // if(instance==null){ // instance=new Instance(); // } // return instance; // } // 2.1懒汉式 线程安全 但是效率低; // private static Instance instance=null; // private static synchronized Instance getInstance(){ // if(instance==null){ // instance=new Instance(); // } // return instance; // } // 3.双重校验锁 这种方式的好处在于在sychronized 之前添加了一次null检查,看似简单,但是他的添加,避免了不必要的加锁处理,提高了并发度,很大程度上提高了性能; // private static volatile Instance instance=null;//volatile 关键字让变量的对其他线程可见 // public static Instance getInstance(){ // if(instance==null){ // synchronized (Instance.class){ // if(instance==null){ // instance=new Instance(); // } // } // } // return instance; // } //4静态内部类的方式;这种方式实现了栏加载,因为Instance 加载后 单例对象并没有实例化,因为InstanceHolder没有被主动调用; // private static class InstanceHolder{ // private static final Instance INSTANCE=new Instance(); //} // public static Instance getinstanse(){ // return InstanceHolder.INSTANCE; // } //5 枚举方法 // enum SingletonDemo { // INSTANCE; // // public void otherMethods() { // System.out.println("Something"); // } // } }
单例模式的总结
最新推荐文章于 2023-06-27 21:57:23 发布