zoukankan      html  css  js  c++  java
  • Java中的单例模式

      

    对象在new的时候就会创建一个新的地址,所以需要将实例先提前初始化为静态的,在调用时直接用类调用,便不需要new出来了

    饿汉式是线程安全的

    懒汉式是非线程安全的

     1 package object.singleton;
     2 
     3 public class Student {
     4     //饿汉式
     5     private static Student student=new Student();//初始化一个实例
     6     
     7     public static Student getInstance(){
     8         
     9         return student;
    10         
    11     }
    12 
    13 }
    结果:

    object.singleton.Student@15db9742
    object.singleton.Student@15db9742

     1 package object.singleton;
     2 
     3 public class Student {
     4     //懒汉式
     5     private static Student student=null;//初始化一个实例
     6     
     7     public static Student getInstance(){
     8         if(student==null){
     9             student=new Student();
    10         }
    11         return student;
    12         
    13     }
    14 
    15 }
    结果:

    object.singleton.Student@15db9742
    object.singleton.Student@15db9742

     1 package object.singleton;
     2 //懒汉式和饿汉式的测试
     3 public class Singleton {
     4     public static void main(String[] args) {
     5         Student stu1=Student.getInstance();
     6         Student stu2=Student.getInstance();
     7         System.out.println(stu1);
     8         System.out.println(stu2);
     9         
    10     }
    11 }
  • 相关阅读:
    “铁大失物帮”Alpha版使用说明
    绩效评估
    改进方案评论
    意见汇总
    对其他团队项目的意见和建议
    冲刺周期
    属于我的专属博客团队地址
    第一个冲刺周期-第三天
    第一个冲刺周期-第二天
    动手动脑与动手
  • 原文地址:https://www.cnblogs.com/ztt0918/p/8073704.html
Copyright © 2011-2022 走看看