设计模式(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);

	}
	// 其它方法
}


 

原文地址:https://www.cnblogs.com/lxjshuju/p/7214136.html