zoukankan      html  css  js  c++  java
  • 辛格尔顿

    辛格尔顿(Singleton),以保证一个类只有一个实例,并提供了一个全球性的接入点访问它。

    因为辛格尔顿Singleton它的类封装的唯一实例,因此,它可以妍格控制客户如何以及何时访问它访问。

    简单地说,它是受控访问的唯一的例子。

    package gof23;
    
    public class SingletonTest {
    	public static void main(String[] args) {
    		Singleton obj1 = Singleton.getInstance();
    		Singleton obj2 = Singleton.getInstance();
    		System.out.println(obj1 == obj2);
    	}
    }
    
    class Singleton {
    	private static Singleton instance = null;
    	
    	private Singleton() {     //构造方法让其private,这就堵死了外界利用new创建此类实例的可能
    		
    	}
    	
    	public static Singleton getInstance(){
    		if(instance == null) {
    			instance = new Singleton();
    		}
    		return instance;
    	}
    }
    
    结果为:

    true

    多线程时的单例

    多线程的程序中,多个线程同一时候,注意是同一时候訪问Singleton类,调用getInstance()方法,会有可能造成创建多个实例,这个时候能够给进程加一把锁进行处理。

    package gof23;
    
    import java.util.concurrent.locks.ReentrantLock;
    
    public class SingletonTest {
    	public static void main(String[] args) {
    		Singleton obj1 = Singleton.getInstance();
    		Singleton obj2 = Singleton.getInstance();
    		System.out.println(obj1 == obj2);
    	}
    }
    
    class Singleton {
    	private static Singleton instance = null;
    	private static ReentrantLock lock = new ReentrantLock();
    	private Singleton() {     //构造方法让其private,这就堵死了外界利用new创建此类实例的可能
    		
    	}
    	
    	public static Singleton getInstance(){
    		if(instance == null) {
    			lock.lock();      //先推断实例是否存在,不存在在加锁处理,能够避免每次调用getInstance方法都须要lock
    			try {
    				if(instance == null) {        //双重锁定
    					instance = new Singleton();
    				}
    			}
    			finally {
    				lock.unlock();      //释放锁
    			}
    		}
    		return instance;
    	}
    }
    

    执行结果为:

    true



    版权声明:本文博客原创文章。博客,未经同意,不得转载。

  • 相关阅读:
    Python基础-数据写入execl
    Python基础-读取excel
    table合并单元格colspan和rowspan
    从PHP客户端看MongoDB通信协议(转)
    win7环境下mongodb分片和移除
    32位下操作mongodb心得
    Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 1099 bytes) in
    js关闭当前页面(窗口)的几种方式
    js页面跳转 和 js打开新窗口 方法
    MongoDB中的_id和ObjectId
  • 原文地址:https://www.cnblogs.com/yxwkf/p/4611121.html
Copyright © 2011-2022 走看看