zoukankan      html  css  js  c++  java
  • 模式的秘密:单例模式

    /*
    *是饿汉模式
    */
    public class Singleton { private Singleton (); private static Singleton Instance =new Singleton (); public static Singleton getInstance (){ return Instance ; } }
    /*
    *懒汉模式
    */ 

      public class Singleton2 {
      //1.将构造方式私有化,不允许外边直接创建对象
      private Singleton2(){

      }  
      //2.声明类的唯一实例
      private static Singleton2 instance;
      //3.提供一个获取实例的方法
      public static Singleton2 getInstance(){
        if(instance == null){
          instance = new Singleton2();
          }
        return instance;
        }
      }

    public class Test{
        public static void main(String[] args){
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
    if(s1==s2){ Systom.out.println("s1和s2是同一实例") }else{ Systom.out.println("s1和s2不是同一实例") } } }

      区别:饿汉模式的特点是加载类时比较慢,但运行时获取对象的速度比较快,线程安全

                      懒汉模式的特点是加载类时比较快,但运行时获取对象的速度比较慢,线程不安全

      

  • 相关阅读:
    Cookies的实际存储位置
    搭建Git本地服务器
    在Tomcat中部署war
    Server.xml配置解析
    Tomcat配置详解,配置文件server.xml详解
    将centos7打造成桌面系统
    英语词汇大全
    商场/超市常见英语标识
    商务英语词汇大全
    常用繁体字大全
  • 原文地址:https://www.cnblogs.com/luffe/p/8494081.html
Copyright © 2011-2022 走看看