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

    1、单例模式是“对象池模式”的一种特殊情况

    2、单例模式要解决的问题是:

        创建对象所付出的代价比较大

        没有必要创建多个问题

        提供一个全局访问点,就像C中的全局变量一样

    3、常见的两种实现机制

    3.1、常见实现一:只要加载Class文件,就创建对象

     1 package com.xinye.test.singleton;
     2 /**
     3  * 单例
     4  * @author xinye
     5  *
     6  */
     7 public class Singleton {
     8     
     9     private static final Singleton INSTANCE = new Singleton();
    10     
    11     private Singleton(){
    12         
    13     }
    14     
    15     public static Singleton getInstance(){
    16         return INSTANCE;
    17     }
    18 }

    3.2、常见的实现二:在第一次使用的时候创建对象,传说中的懒加载方式

      注意:

        这种情况下,如果使用在多线程环境中,需要使用同步机制

        对于一定会使用到这个单例的情况下,这种实现方式就比较扯淡了

              只有在创建这个对象代价特别大的情况下,懒加载的情况才有意义
        

     1 package com.xinye.test.singleton;
     2 /**
     3  * 
     4  * @author xinye
     5  *
     6  */
     7 public class SingletonLazy {
     8     
     9     private static SingletonLazy instance = null;
    10     
    11     private SingletonLazy(){
    12         
    13     }
    14     public synchronized static SingletonLazy getInstance(){
    15         if(instance == null){
    16             instance = new SingletonLazy();
    17         }
    18         return instance;
    19     } 
    20 }

    还有其他的实现单例模式的方法,比如静态私有内部类的方式,但造成代码可读性很垃圾,所以,永远不用那个!

    3.3、使用示例:

     1 package com.xinye.test.singleton;
     2 /**
     3  * 
     4  * @author xinye
     5  *
     6  */
     7 public class TestSingleton {
     8 
     9     public static void main(String[] args) {
    10         Singleton s1 = Singleton.getInstance();
    11         Singleton s2 = Singleton.getInstance();
    12         
    13         System.out.println(s1);
    14         System.out.println(s2);
    15         
    16         SingletonLazy sl1 = SingletonLazy.getInstance();
    17         SingletonLazy sl2 = SingletonLazy.getInstance();
    18         
    19         System.out.println(sl1);
    20         System.out.println(sl2);
    21     }
    22 
    23 }
  • 相关阅读:
    ansible4:playbook介绍及使用
    ansible3:模块介绍
    Rabin加密算法
    基础业务:图片懒加载
    基础业务:滚动到指定位置导航固定(CSS实现)
    数据库事务处理的并发控制技术(二):事务模型
    详解HTTP缓存
    数据库事务处理的并发控制技术(一):并发控制概述
    二叉树的深度优先遍历和广度优先遍历
    Virtual DOM的简单实现
  • 原文地址:https://www.cnblogs.com/xinye/p/3907363.html
Copyright © 2011-2022 走看看