Is there a way to automatically call a particular method immediately after all constructors have run?

前端 未结 4 1878
独厮守ぢ
独厮守ぢ 2021-02-12 12:54

I want to be able to call a particular method automatically upon construction of a derived object, however I can\'t think how to do it. The following code illustrates. Another a

4条回答
  •  太阳男子
    2021-02-12 13:36

    This sounds like a good candidate for a factory. Make all the constructors private or protected, requiring consumers of your code to call the factory method when they want an instance of your object. In the factory method, you use the new operator to create the object, and then call DoThisAutomaticallyAfterConstruction() before returning the object.

    EDIT

    A factory may be a static method, or you may have a factory object. See, for example, Wikipedia on the abstract factory pattern at http://en.wikipedia.org/wiki/Abstract_factory_pattern, and the documentation for the ADO.NET DbProviderFactories at http://msdn.microsoft.com/en-us/library/wda6c36e.aspx for a real-world implementation.

提交回复
热议问题