使用工厂方法为继承的类构造基础对象

时间:2014-03-06 17:05:00

标签: c# inheritance factory

我有一个课程,类似这样:

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";
}

我想摆脱使用构造函数来创建这些对象以支持工厂方法,但我不是在不调用构造函数的情况下如何分配基础实例/对象。这可能吗?

1 个答案:

答案 0 :(得分:2)

工厂方法知道如何创建类的特定实例,通常不是基类。相反,为此,您可以在基类上拥有受保护的构造函数:

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