zoukankan      html  css  js  c++  java
  • 设计模式(四)—— 单例模式

    单例模式属于对象创建性质的模式,用于产生一个对象的具体实例,并且可以确保系统中一个类只能产生一个实例。

    饥饿式单例

    public class Singleton {
    	private  static Singleton singleton = new Singleton();
    	private Singleton(){
    		System.out.println("Singleton is create");
    	}
    	public static Singleton getInstance(){
    		return singleton;
    	}
    }
    

    懒汉式单例

    public class LazySingleton {
    
    	private LazySingleton(){
    		System.out.println("LazySingleton is create");
    	}
    	private static LazySingleton instance = null;
    	public static synchronized LazySingleton getInstance(){
    		if(instance==null)
    			instance = new LazySingleton();
    		return instance;
    	}
    }
    

    内部类式单例

    public class StaticSingleton {
    	
    	private StaticSingleton(){
    		System.out.println("Static Singleton is create");
    	}
    	private static class SingletonHolder{
    		private static StaticSingleton instance = new StaticSingleton();
    	}
    	public static final StaticSingleton getInstance(){
    		return SingletonHolder.instance;
    	}
    }
    

    性能比较

    创建5个线程,模拟多线程环境下的性能

    public class Client implements Runnable{
    	public static void main(String[] args) {
    		Client client = new Client();
    
    		new Thread(client).start();
    		new Thread(client).start();
    		new Thread(client).start();
    		new Thread(client).start();
    		new Thread(client).start();
    
    
    	}
    
    	@Override
    	public void run() {
    		long begintime = System.currentTimeMillis();
    		for(int i = 0;i<100000;i++)
    			StaticSingleton.getInstance();
    		System.out.println("spend:"+(System.currentTimeMillis()-begintime));
    	}
    }
    

    两次比较

    懒汉式 185ms 190ms
    饥饿式 54ms 49ms
    内部类式 56ms 61ms
    在多线程条件下,懒汉式单例耗时要比饥饿式耗时要多很多,因为懒汉式为了使用延迟加载而引入了同步关键字,降低了系统性能
    而内部类式单例既可以做到延迟加载,又不必使用同步关键字,是一种比较完善的实现。

    双检查的懒汉单例模式

  • 相关阅读:
    Scrum:The Definition of Done —— 作业有没有写完呢?
    中兴通讯 可视化devops 牛啊 屠亚奇
    qunar-dns
    通过业务系统的重构实践DDD
    通过业务系统的重构实践DDD
    一键部署Kubernetes高可用集群
    springboot系列
    Ubuntu · Docker —— 从入门到实践
    容器化操作系统概览
    基于 CentOS7 的 Kubernetes 集群
  • 原文地址:https://www.cnblogs.com/fonxian/p/5447034.html
Copyright © 2011-2022 走看看