2014-03-06 45 views
0

我有一個類,像這樣:使用工廠方法來構建基礎對象繼承

public class User { 
    public User() { 
    // this constructor creates an object representing a brand new user 
    } 

    public static User Get(MyDbObject dbObject) { 
    // this factory method creates an object representing an existing user, from a database object 
    } 
} 

和繼承的類,像這樣:

public class ExtendedUser : User { 
    public object ExtendedProperty { get; set; } 

    public static ExtendedUser Get(MyDbObject dbObj) { 
    User usr = User.Get(dbObj); 
    this = usr; // this does NOT work 
    this.ExtendedProperty = "just an example"; 
    } 
} 

本來這是所有工作使用從MyDbObject記錄創建一個對象的重載構造函數,因此ExtendedUser具有這樣的構造函數:

public ExtendedUser(MyDbObject dbObj) : base(dbObj) { 
    this.ExtendedProperty = "another example, this is how it WAS working"; 
} 

我想擺脫使用構造函數來創建這些對象,而傾向於工廠方法,但是我不會在不調用構造函數的情況下分配基本實例/對象。這可能嗎?

+0

不,不可能。 – MarcinJuraszek

+0

爲什麼你想使用工廠方法而不是構造函數? – khellang

回答

1

工廠方法知道如何創建類的特定實例,通常不是基類。相反,您可以在基類上擁有一個受保護的構造函數以實現此目的:

public class User { 
     public User() { 
     // this constructor creates an object representing a brand new user 
     } 

     protected User(MyDbObject dbObject) { 
     // creates an object representing an existing user, from a database object 
     } 

     public static User GetUser(MyDbObject dbObject) { 
     return User(dbObject); 
     } 
    } 

    public class ExtendedUser : User { 
     public object ExtendedProperty { get; set; } 

     private ExtendedUser(MyDbObject dbObject) : base(dbObject) 
     { 
     //add extra data onto the base class here 
     } 

     public static ExtendedUser GetExtendedUser(MyDbObject dbObj) { 
     return new ExtendedUser(dbObject); 
     } 
    } 
+0

啊哈,完美。謝謝! – DaveD

+0

無意中使基類和繼承類具有相同的靜態方法...我修改了它。 –