简体   繁体   中英

Apply recurring conditional check to all derived classes

I got a job base class with an abstract Work() method. This gets overridden/implemented in my inherited classes.

What I want to achieve is applying an abort condition to all derived classes. The template method pattern doesn't seem to help me here, because I need this check to occur in my abstract Work()-class.

A workaround would be making Work() virtual, but then I'm no longer forcing the implementation of it (what I want to do):

public abstract class First
{
    protected virtual void Work()
    {
        //do stuff
    }
}

public class Second : First
{
    protected override void Work()
    {
        base.Work();
    }
}

Is there any way to achieve my goal?

The template method pattern doesn't seem to help me here, because I need this check to occur in my abstract Work()

You picked the right pattern, but you did not apply it properly.

The idea behind the template method pattern is to make Work non-virtual, and provide a separate method, virtual or abstract, for subclasses to override. This way all the checks that could abort a job would be performed in the Work function of the base class, while the derived classes would provide actual implementations for what to do when the checks have succeeded:

public abstract class First {
    public void Work() {
        if (!CheckPreconditions()) {
            // Abort the job
            return;
        }
        DoWork();
    }
    protected abstract void DoWork();
}

public class Second : First {
    protected override void DoWork() {
        // Do the actual work here
    }
}

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