【编程题】请设计一个类,该类在同一个进程中只能由一个实例,且该实例允许外部访问。
using System; using System.Collections.Generic; namespace Test { public class Player { public string name; public string gender;public static Player GetInstance() { if(_instance==null) { _instance=new Player(); } return _instance; }private Player()
{
}
private static Player _instance;
}
class Program
{
static void Main(string[] args)
{
Player p=Player.GetInstace();
p.name="张三";
p.gender="男";
}
}
}
2.在类中创建静态私有的实例,在需要时创建该实例,直到程序结束才销毁。
3.提供一个静态的公有的函数用于创建/获取静态私有对象。
public class Singleton {
private static Singleton uniqueInstance = null;
private Singleton() {
// Exists only to defeat instantiation.
}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// Other methods...
}
public class Singleton {// 使用 transient 关键字防止反序列化private volatile transient Singleton instance = null;private Singleton(){}public static Singleton getInstance() {if(instance == null) {// 当多个线程在此竞争锁时,仅有一个线程获取到锁执行临界区代码synchronized(Singleton.class) {// 第二次检查,避免多个线程进入后反复初始化,违背单例模式if(instance == null) {// 当第一个获取到锁的线程执行到此时,为了避免指令重排序造成未初始化完成就返回实例,// 此时实例判断不为 null,其他线程可能返回一个未初始化的实例,所以使用 volatile 关键字防止指令重排。instance = new Singleton();}}}return instance;}}
package singleton; public class God { private static God god=new God(); private String name="上帝"; private String gender="男"; private God() {} public static God newInstance() { return god; } public String getName() { return name; } public String getGender() { return gender; } }
package singleton; public class GodTest { public static void main(String[] args) { God god1 = God.newInstance(); God god2 = God.newInstance(); System.out.println(god1.getName()); //上帝 System.out.println(god1==god2); //true } }