gpt4 book ai didi

c# - 我怎样才能让一个类(class)单独负责创建和提供对另一个类(class)的访问

转载 作者:太空宇宙 更新时间:2023-11-03 14:32:19 25 4
gpt4 key购买 nike

这就是我如何理解我可以在 C# 中实现单例模式:

public class ChesneyHawkes{
private static ChesneyHawkes _instance = new ChesneyHawkes();
public ChesneyHawkes Instance {get{return _instance;}}

private ChesneyHawkes()
{
}

}

如果我想提供一个对象的单个实例,以便永远只有一个,将对它的访问公开,但只允许它被创建或由另一个单例替换。

//   The PuppetMaster should be the only class that 
// can create the only existing Puppet instance.

public class PuppetMaster{

private static PuppetMaster_instance = new PuppetMaster();
public static PuppetMaster Instance {get{return _instance;}}

// Like a singleton but can be replaced at the whim of PuppetMaster.Instance
public static Puppet PuppetInstance {get {return Puppet;}}

private PuppetMaster()
{

}

public class Puppet{
// Please excuse the pseudo-access-modifier
puppetmasteronly Puppet(){

}
}
}


// To be accessed like so.
PuppetMaster.Puppet puppet = PuppetMaster.Instance.PuppetInstance;

最佳答案

你真的不需要一个以上的单例。看这个例子:

using System;

// interface for the "inner singleton"
interface IPuppet {
void DoSomething();
}

class MasterOfPuppets {

// private class: only MasterOfPuppets can create
private class PuppetImpl : IPuppet {
public void DoSomething() {
}
}

static MasterOfPuppets _instance = new MasterOfPuppets();

public static MasterOfPuppets Instance {
get { return _instance; }
}

// private set accessor: only MasterOfPuppets can replace instance
public IPuppet Puppet {
get;
private set;
}
}

class Program {
public static void Main(params string[] args) {
// access singleton and then inner instance
MasterOfPuppets.Instance.Puppet.DoSomething();
}
}

关于c# - 我怎样才能让一个类(class)单独负责创建和提供对另一个类(class)的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2319307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com