Naming convention for non-virtual and abstract methods

前端 未结 8 1117
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-05 02:49

I frequently find myself creating classes which use this form (A):

abstract class Animal {
  public void Walk() {
    // TODO: do something before walking

    /         


        
8条回答
  •  太阳男子
    2021-02-05 03:31

    One name for this pattern is "Template Method Pattern"

    In C#, the method to be overridden by a derived class is preceded by "On". The logic behind this naming is that the derived class is custom responding to what is conceptually an internal event. This led to some confusion with C#'s other, now deprecated, use of "On" for raising events, but that's an old C# specific problem and it doesn't really exist anymore.

    class BaseClass
    {
        protected virtual void OnInitialize() {};
        private PreInitialize() {}
        private PostInitialize() {}
        void Initialize()
        {
           PreInitialize();
           OnInitialize();
           PostInitialize();
        }
    }
    
    class DerivedClass : BaseClass
    {
        protected override void OnInitialize() { /*do whatever*/ }
    }
    

提交回复
热议问题