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

      创建型模式

      单例模式:在程序运行过程中采用该模式的类只有一个对象实例,

      要实现该结果要保证私有化构造器,使其只能在类的内部生成实例对象;同时还要提供给外部获取该实例的方法,该实例只能是同一个,所以需要加static关键字;方法返回该实例对象,所以该方法也需要是静态方法。

    实现一:饿汉式

      优点:线程安全

      缺点:实例加载时间长(该实例在类加载开始就加载在内存中,直到类的生命周期结束)

    class HungryBoy{
    	private HungryBoy(){}
    	
    	private static HungryBoy instance = new HungryBoy();
    	
    	public static HungryBoy getInstance() {
    		return instance;
    	} 
    }
    

    实现二:懒汉式 

      优点:延迟加载实例

      缺点:线程不安全

    class LazyBoy{
    	private LazyBoy() {}
    	
    	private static LazyBoy instance= null;
    	
    	public static LazyBoy getInstance() {
    		if(instance != null) {
    			instance = new LazyBoy();
    		}
    		return instance;
    	}
    	
    }
    

    实现三:懒汉式(线程安全版)

    public class LazyBoy {
    
        private LazyBoy(){    }
    
        private static LazyBoy instance = null;
    
        public static LazyBoy getInstance() {
            if(instance == null){
                synchronized (LazyBoy.class){		//这样做效率更高
                    if(instance == null){
                        instance = new LazyBoy();
                    }
                }
            }
            return instance;
        }
    }
    

      

  • 相关阅读:
    异常处理(五)
    抽象与接口(七)
    MYSQL创建数据库时候直接指定编码和排序规则
    C#基本语法(一)
    C#中字符串处理(三)
    Ajax实例化(五)
    C#函数(二)
    MemberCache学习摘要
    ORACLE 根据日期范围自动日期table
    动态执行SQL语句,并输出参数
  • 原文地址:https://www.cnblogs.com/MT-1996/p/13027831.html
Copyright © 2011-2022 走看看