雖然我試圖尋找使用私人構造函數,我發現的所有是它在Singleton模式中的使用。 除Singleton模式外什麼是私有構造函數。 一些鏈接或代碼示例將不勝感激。私人構造函數以外的任何其他用途單身模式
0
A
回答
0
從初始化對象時使用私有構造函數。一個靜態搜索(...)函數後面的DataReader - 這樣的構造函數在公開的時候沒什麼意義。
3
以下是另外兩個原因:
工廠模式。
- 使用私有構造函數和公共靜態方法來調用它們。
不可變類的Builder模式。
- 使用嵌套的可變Builder構造類,其中的一個實例被傳遞給一個私有構造函數。
樣品Builder模式:
using System;
namespace Demo
{
public static class Program
{
public static void Main(string[] args)
{
var demo = new ImmutableClass.Builder{
A = 1,
B = "two",
C = 3.0
}.Build();
}
}
public sealed class ImmutableClass
{
public sealed class Builder
{
public int A;
public string B;
public double C;
public ImmutableClass Build()
{
return new ImmutableClass(this);
}
}
private ImmutableClass(Builder builder)
{
_a = builder.A;
_b = builder.B;
_c = builder.C;
}
public int A
{
get
{
return _a;
}
}
public string B
{
get
{
return _b;
}
}
public double C
{
get
{
return _c;
}
}
private readonly int _a;
private readonly string _b;
private readonly double _c;
}
}
2
快速回答:系列化和鏈構造。
較長的答案:
對象的序列化,需要初始化
public class SomeSerializableClass {
private SomeSerializableClass() {} // Used only in serialization
public SomeSerializableClass(int initParameter){
this.Property = initParameter;
}
public int Property { get; set; }
}
public class Program{
static void Main(){
var obj1 = new SomeSerializableClass(42); // valid
var obj2 = new SomeSerializableClass(); // invalid
var xs = new XmlSerializer(typeof(SomeSerializableClass));
var obj3 = (SomeSerializableClass)xs.Deserialize(someStream); // possible
}
}
連鎖構造函數(因式分解一些構造邏輯)值:
public class SomeClass {
private SomeClass(int initParameter) {
this.Property = initParameter; // Will always be executed, the logic exists once
}
public SomeSerializableClass(int initParameter, string otherParameter)
: this(initParameter)
{
}
public SomeSerializableClass(int initParameter, int againAntherParameter)
: this(initParameter)
{
}
public int Property { get; set; }
}
相關問題
- 1. 如何從多個私人構造函數中反映私人構造函數
- 2. 模板化單例類 - 如何處理私人構造函數
- 3. 調用其他構造函數的構造函數:任何性能問題?
- 4. 如何在其他構造函數中調用構造函數?
- 5. 構造函數的私人範圍
- 6. 構造函數中的調用基構造函數和其他構造函數
- 7. 使用mockito的模擬私人構造函數
- 8. 嘲笑私人構造函數
- 9. Ninject和私人構造函數
- 10. KScenemer在Lucene有私人構造函數
- 11. 私人WCF服務構造函數
- 12. 私人拷貝構造函數:disallow
- 13. Xposed - 掛鉤私人構造函數
- 14. 私人構造函數在單例設計模式中需要什麼?
- 15. 構造函數調用其他構造函數
- 16. 私人構造函數或私有函數?
- 17. C++單身使用:編譯器抱怨私有構造函數
- 18. PHP設計模式:私有構造函數是否對您允許其他人擴展的類不利?
- 19. 私人類構造函數不能訪問私人成員
- 20. 單身設計模式 - 明確指出類之外的構造函數
- 21. 如何從c#中的構造函數調用其他構造函數?
- 22. 重用私人jQuery函數在其他模塊
- 23. 由其他調用構造函數
- 24. 私人類的構造函數是否必須是私有的?
- 25. 在java中,如何使用其父類也有私有構造函數的私有構造函數創建類?
- 26. 構造函數鏈的用途?
- 27. 功能模板和私人拷貝構造函數
- 28. 使用反射的參數化私人構造函數
- 29. 是一個私有構造函數的默認構造函數,它的用途是什麼?
- 30. unique_ptr成員,私人拷貝構造函數與移動構造函數
沮喪,有沒有「遷移到programmers.stackexchange「選項。我想這在那邊會更好。 – spender 2013-03-22 13:18:55
顯然是工廠模式。一直使用。 – 2013-03-22 13:19:22
http://stackoverflow.com/questions/2585836/why-do-we-need-a-private-constructor?rq=1 – spender 2013-03-22 13:20:24