如何让一个班级单独负责创建和提供对另一个班级的访问权限

时间:2010-02-23 15:29:23

标签: c# design-patterns singleton

我理解这可以在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;

1 个答案:

答案 0 :(得分:1)

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

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();
    }
}