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

    单例设计模式:

    定义:

    确保一个类仅仅有一个实例,而且自行实例化。并向整个系统提供这个实例。

    饿汉式:

    class Single {
    	private static final Single s = new Single();
    
    	// 限制产生多个对象
    	private Single() {
    	}
    
    	// 通过该方法获得实例对象
    	public Single getInstance() {
    		return s;
    	}
    
    	// 类中其它方法尽量使用static
    	public static void say() {
    		System.out.println("--> only one");
    	}
    }


     

    通过定义一个私有訪问权限的构造函数,避免被其它类new出来一个对象。

    懒汉式:

    考虑到线程同步的问题。

    /*懒汉式
     * 延迟载入
     * */
    class Single1
    {
        private static Single1 s = null;
        private Single1() {}
    
        public static Single1 getInstance()
        {
            if ( s == null)
            {
                synchronized (Single1.class)
                {
                    if (s == null)
                        s = new Single1();
                }
            }
            return s;
        }
    }


     

    单例模式的扩展:产生固定数量的对象。

    class Single {
    	// 固定数量
    	private static int num = 5;
    	private static ArrayList<String> nameList = new ArrayList<String>();
    	private static ArrayList<Single> singleList = new ArrayList<Single>();
    	private static int currentNum = 0;
    	static {
    		for (int i = 0; i < num; i++) {
    			singleList.add(new Single("num + " + (i + 1)));
    		}
    	}
    
    	private Single(String name) {
    		nameList.add(name);
    	}
    
    	public static Single getInstance() {
    		Random random = new Random(num);
    		currentNum = random.nextInt();
    		return singleList.get(currentNum);
    
    	}
    	// 其它方法
    }


     

  • 相关阅读:
    SQL Server经典函数之数字去零
    c# 定时执行python脚本
    SQL Server 存储过程生成流水号
    MySQL删除数据表中重复数据
    js封装正则验证
    .NET中将中文符号转换成英文符号
    WebApi中跨域解决办法
    JS生成GUID方法
    LINQ中的连接(join)用法示例
    LINQ分组取出第一条数据
  • 原文地址:https://www.cnblogs.com/lxjshuju/p/7214136.html
Copyright © 2011-2022 走看看