zoukankan      html  css  js  c++  java
  • (四)单例模式-代码实现

    介绍

    概念:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

    使用场景:整个项目中只能创建一次对象的类.防止出现多个对象同时存在.如:数据库连接池,有多个就不能有效控制连接数了.

     两种实现方式

    第一种:

    //单例类

    package note.com.singleton;
    
    public class Singleton {
        private static Singleton singleton = null;
        private Singleton(){
        }
        
        public static synchronized Singleton getSingleton(){//synchronized是必须的
            if(singleton==null){
                singleton = new Singleton();
            }
            return singleton;
        }
        
    }

    //测试类

    package note.com.singleton;
    
    public class SingletonTest {
        public static void main(String[] args) {
            Singleton s11 = Singleton.getSingleton(); 
            Singleton s12 = Singleton.getSingleton(); 
            System.out.println(s11);
            System.out.println(s12);
        }
    }

    //结果

    note.com.singleton.Singleton@659e0bfd
    note.com.singleton.Singleton@659e0bfd

    第二种:

    //单例类

    package note.com.singleton;
    
    public class Singleton2 {
        private static Singleton2 singleton = new Singleton2();
        private Singleton2(){
            
        }
        public static Singleton2 getSingleton2(){
            return singleton;
        }
    }

    //测试类

    package note.com.singleton;
    
    public class SingletonTest {
        public static void main(String[] args) {
            Singleton2 s11 = Singleton2.getSingleton2(); 
            Singleton2 s12 = Singleton2.getSingleton2(); 
            System.out.println(s11);
            System.out.println(s12);
        }
    }

    //结果

    note.com.singleton.Singleton2@659e0bfd
    note.com.singleton.Singleton2@659e0bfd

  • 相关阅读:
    linux安装mysql5.6全流程
    linux安装redis集群全流程
    脑图-流程图-ppt制作工艺
    控制台添加log4net
    正则表达式非获取匹配的用法
    Win10查看已存储WiFi密码的两种方法
    redis中list set zset的区别
    Topshelf 搭建 Windows 服务
    SQLSERVER 自增列跳ID 1W-1K问题
    sqlserver 自增列(id)跳跃问题,一下就跳过一千多个id
  • 原文地址:https://www.cnblogs.com/qinggege/p/5230861.html
Copyright © 2011-2022 走看看