zoukankan      html  css  js  c++  java
  • 单例模式典型创建方法(三种)

    单线程

     
    class Singleton {
    	
    	private Singleton() {};
    	private static Singleton instance = null;
    	
    	public static Singleton createInstance() {
    		if (instance == null) {
    			instance = new Singleton();
    		}
    		return instance;
    	}
    	
    }
     
    public class HelloWorldjava {
    
    	public static void main(String[] args) {
    		Singleton s1 = Singleton.createInstance();
    		Singleton s2 = Singleton.createInstance();
    		
    		if (s1 == s2) {
    			System.out.println("只有一个实例被创建!");
    		}
    	}
    }
    
     

    预先加载

    class Singleton {
    	
    	private Singleton() {};
    	private static Singleton instance = new Singleton();
    	
    	public static Singleton createInstance() {
    		return instance;
    	}
    	
    }
    
    
    public class HelloWorldjava {
    
    	public static void main(String[] args) {
    		Singleton s1 = Singleton.createInstance();
    		Singleton s2 = Singleton.createInstance();
    		
    		if (s1 == s2) {
    			System.out.println("只有一个实例被创建!");
    		}
    	}
    }
    

    按需创建

    class Singleton {
    	
    	private Singleton() {};
    	
    	private static class Helper {
    		static Singleton instance = new Singleton(); 
    	}
    	
    	public static Singleton createInstance() {
    		return Helper.instance;
    	}
    	
    }
    
    public class HelloWorldjava {
    
    	public static void main(String[] args) {
    		Singleton s1 = Singleton.createInstance();
    		Singleton s2 = Singleton.createInstance();
    		
    		if (s1 == s2) {
    			System.out.println("只有一个实例被创建!");
    		}
    	}
    }
    
  • 相关阅读:
    博客园风格简单修饰(Do It Yourself)
    十大经典排序算法
    物流BOS
    算法设计
    牛客网刷题
    关于上网的问题
    Lucene&Solr
    SSM综合练习
    四十八:WAF绕过-权限控制之代码混淆及行为造轮子
    四十七:WAF绕过-漏洞发现之代理池指纹被动探针
  • 原文地址:https://www.cnblogs.com/helloweworld/p/3045224.html
Copyright © 2011-2022 走看看