⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 client.java

📁 设计模式描述设计模式描述设计模式描述设计模式描述
💻 JAVA
字号:
/*
 * Created on 2005-5-7
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.test.pattern.create.signleton;

/**
 * @author Administrator
 * 
 * 意图 保证一个类仅有一个实例,并提供一个访问它的全局访问点。 适用性 当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时。
 * 当这个唯一实例应该是通过子类化可扩展的, 并且客户应该无需更改代码就能使用一个扩展的实例时。
 *  
 */
class Singleton {
	private static Singleton _instance;

	public static Singleton Instance() {
		if (_instance == null)
			_instance = new Singleton();
		return _instance;
	}

	private Singleton() {
	}

	// Just to prove only a single instance exists
	private int x = 0;

	public void SetX(int newVal) {
		x = newVal;
	}

	public int GetX() {
		return x;
	}
}

/// <summary>
/// Summary description for Client.
/// </summary>

public class Client {
	public static void main(String[] args) {
		int val;
		// can't call new, because constructor is protected
		Singleton FirstSingleton = Singleton.Instance();
		Singleton SecondSingleton = Singleton.Instance();

		// Now we have two variables, but both should refer to the same object
		// Let's prove this, by setting a value using one variable, and
		// (hopefully!) retrieving the same value using the second variable
		FirstSingleton.SetX(4);
		System.out.println("Using first variable for singleton, set x to 4");

		val = SecondSingleton.GetX();
		System.out
				.println("Using second variable for singleton, value retrieved = "
						+ val);

	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -