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);
          }
      }

      

  • 相关阅读:
    POJ 3276 Face The Right Way
    POJ 3061 Subsequence
    HDU 2104 hide handkerchief
    GCJ Crazy Rows
    HDU 1242 Rescue
    激光炸弹:二维前缀和
    I Hate It:线段树:单点修改+区间查询
    承压计算:模拟+double
    等差素数列:线性筛+枚举
    Period :KMP
  • 原文地址:https://www.cnblogs.com/tysl/p/10035459.html
Copyright © 2011-2022 走看看