简体   繁体   中英

abstract class vs calling base

I need to give the user some degree of control over a function. So I want to partially implement a class that the user can fully implement. I came up with this solution.

public abstract class A
{
    protected void FunctionA()
    {
        // My implementation here
        FunctionB();
    }

    protected abstract void FunctionB();
}

public class B : A
{
    protected override void FunctionB()
    {
        // User implementation here
    }
}

The other solution is this

public class A
{
    protected virtual void FunctionB()
    {
        // My implementation here
    }
}

public class B : A
{
    protected override void FunctionB()
    {
        base.FunctionB();
        // User implementation here
    }
}

Is there any reason I should use one of these solutions over the other? Does it provide some sort of advantage? Could someone give me some insight on when I should use one solution and not the other?

Your first solution is actually a well known pattern, called the Template Method pattern . It's a good approach if you want to make sure the base method is executed (because FunctionA might do others things besides calling FunctionB ).

In the second solution, it becomes possible for the overriding method to not call the base method. Depending on your scenario, it might be appropriate, or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM