首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何让一个类单独负责创建和提供对另一个类的访问

如何让一个类单独负责创建和提供对另一个类的访问
EN

Stack Overflow用户
提问于 2010-02-23 23:29:23
回答 1查看 151关注 0票数 2

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

代码语言:javascript
复制
public class ChesneyHawkes{
    private static ChesneyHawkes _instance = new ChesneyHawkes();
    public ChesneyHawkes Instance {get{return _instance;}}

    private ChesneyHawkes()
    {
    }

}

如果我想要提供一个对象的单个实例,这样就只能有一个对象,那该怎么办呢?将对它的访问设置为公共的,但只允许它被另一个单例创建或替换。

代码语言:javascript
复制
//   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;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-02-23 23:46:30

为此,您实际上不需要多个单例。看看这个例子:

代码语言:javascript
复制
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();
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2319307

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档