2010-02-23 75 views
2

這是我的理解,我可以實現在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; 
+0

您是否在嘗試在詢問之前搜索此站點以獲取「Singleton」? – 2010-02-23 15:37:59

回答

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

謝謝我認爲這符合我想要做的事情,但其他類也可以實現IPuppet,因此可能不會,但可能會在我的項目中使用多個IPuppet。 我真的想要一個對象,一次只能有一個實例,但可以通過多次創建它來替換它。然而,在我認爲使我成爲語言的一個糟糕用戶的時候,我並不善於在Interfaces中思考,這是我真正需要提高我對它的理解的東西。你的例子當然允許私人創作和公共訪問,所以謝謝你。 – Grokodile 2010-02-23 16:39:52

+0

確實有人可能實現IPuppet,但本例中的接口和單例類明確瞭如何使用它們,這是非常重要的事情,因爲您無法防止您的應用程序發生任何可能的誤用。即使使用常規的單例,有人可能仍然使用反射來實例化額外的實例... – 2010-02-23 16:46:59

相關問題