UNeverNo
UNeverNo

Reputation: 583

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?

Upvotes: 1

Views: 43

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

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

Upvotes: 2

Related Questions