• 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 }
  • 相关阅读:
    JSR303实现数据校验案例
    maven安装和相关配置
    mybatis分页插件使用案例
    分页查询案例
    ssm整合相关配置
    配置文件没有按照maven约定存放解决方法
    git常用命令和基本使用
    mybatis配置二级缓存
    Angular第三方UI组件库------ionic
    Angular路由知识点
  • 原文地址:https://www.cnblogs.com/ztt0918/p/8073704.html
Copyright © 2020-2023  润新知