zoukankan      html  css  js  c++  java
  • java设计模式之单例设计模式

    单例设计模式

    1. 保证一个类在使用过程中,只有一个实例。优势就是他的作用,这个类永远只有一个实例。
    2. 优势:这个类永远只有一个实例,占用内存少,有利于Java垃圾回收。

    单例设计模式关键点

    1. 私有的构造方法。
    2. 提供一个外界能够访问的方法。 

    单例模式代码演示

    1. 懒汉模式(延迟加载)
      package test;
      //懒汉模式
      public class Teacher {
          private static Teacher tea=null;
          private Teacher(){}//提供私有的构造方法
          //提供外界能够访问的静态方法
          public static Teacher getTeacher(){
              if(tea==null){
                  tea=new Teacher();
              }
              return tea;
          }
      }
    2. 饿汉模式(饿汉式是线程安全的,在类创建的同时就已经创建好一个静态的对象供系统使用,以后不在改变。)
      package test;
      //懒汉模式
      public class Teacher {
          private static Teacher tea=null;
          private Teacher(){}//提供私有的构造方法
          //提供外界能够访问的静态方法
          public static Teacher getTeacher(){
              if(tea==null){
                  tea=new Teacher();
              }
              return tea;
          }
      }
    3. 测试类:
      package test;
      
      public class Test {
          public static void main(String[] args) {
              Student student = Student.getStudent();
              System.out.println(student);
              Teacher teacher = Teacher.getTeacher();
              System.out.println(teacher);
          }
      }

      

  • 相关阅读:
    About learn《The C programming Language,Second Edition》
    Reproduction CVE_2019_0708
    Hello universe!
    WebSessionStore: Could not obtain reference to HttpContext
    oracle 触发器
    IE11,用Forms身份验证保存不了Cookie
    水晶报表
    SAP记账期间变式
    SAP会计年度变式
    SAP OB52会计年度变式
  • 原文地址:https://www.cnblogs.com/tysl/p/10035459.html
Copyright © 2011-2022 走看看