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不是同一实例") } } }

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

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

      

  • 相关阅读:
    静态(static)、虚拟(virtual)、动态(dynamic)或消息处理(message)
    SQLLITE
    SQLite数据表和视图
    SQLite
    DELPHI 泛型
    indy10 学习2
    indy10 线程池
    indy
    Indy10 控件的使用(2)TidTCpServer组件学习
    Socket心跳包机制
  • 原文地址:https://www.cnblogs.com/luffe/p/8494081.html
Copyright © 2011-2022 走看看