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

    单例模式是一种最常见的设计模式,校招中如果要进大公司,必须透彻的掌握单例模式,总结了常见的一些单例模式

    首先是最简单的恶汉模式,恶汉模式是一种最简单的单例模式

    	/**
    	 * 恶汉模式
    	 */
    public class SingleTon {
    	private static final SingleTon instance = new SingleTon();
    	private SingleTon(){
    		
    	}
    	public static SingleTon getInstance() {
    		return instance;
    	}
    }
    

      其实是懒汉加载模式,最简单的懒汉加载模式如下

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

    但上述懒汉模式是线程不安全的,可以对其进行加锁

    public class SingleTon {
    	private static SingleTon instance = null ;
    	private SingleTon(){
    		
    	}
    	public static synchronized SingleTon getInstace(){
    		if (instances == null ) {
    			return instances = new SingleTon();
    		}
    		return instances;
    	}
    }
    

      或者双重加锁模式

    public class SingleTon {
    	private static SingleTon instance = null ;
    	private SingleTon(){
    		
    	}
    	public static SingleTon getInstance(){
    		if (instances == null) {
    			synchronized (SingleTon.class) {
    				instances = new SingleTon();
    			}
    		}
    		return instances;
    	}
    }
    

      

    单例模式还可以用内部类来实现

          
    public class SingleTon {
          public static class SingleTonHolder{
    		private static SingleTon instance = new SingleTon();
    	}
    
    	public SingleTon() {
    	}
    	public static SingleTon getInstance() {
    		return SingleTonHolder.instance;
    	}
    }    
    

    看看大牛Jon Skeet是怎么写单例的 (c#版)

    public sealed class Singleton
    {
        Singleton()
        {
        }
    
        public static Singleton Instance
        {
            get
            {
                return Nested.instance;
            }
        }
    
        class Nested
        {
            // Explicit static constructor to tell C# compiler
            // not to mark type as beforefieldinit
            static Nested()
            {
            }
    
            internal static readonly Singleton instance = new Singleton();
        }
    }
    有任何疑问可联系本人huwei08@baidu.com
  • 相关阅读:
    30分钟用Restful ABAP Programming模型开发一个支持增删改查的Fiori应用
    SAP Marketing Cloud功能简述(一) : Contacts和Profiles
    如何使用点击超链接的方式打开Android手机上的应用
    1036. Boys vs Girls (25)
    Yet another A + B
    1033. To Fill or Not to Fill (25)
    1032. Sharing (25)
    1021. Deepest Root (25)
    1017. Queueing at Bank (25)
    1016. Phone Bills (25)
  • 原文地址:https://www.cnblogs.com/huwei0814/p/3840387.html
Copyright © 2011-2022 走看看