John m
John m

Reputation: 79

Java pattern to enforce methods are ran

I am racking my brain for a solution. I am sure its something small I am overlooking. I want a way to enforce a method is filled out and ran. So for example, I want a migration class

public interface IMigration
{
   boolean preConditionCheck();

   boolean runMigration();

   boolean postCondition();
}

I want the method preConditionCheck and postCondition to run after the run migration step.

With the interface you have to fill it out but nothing says it has to be ran.

Is there a pattern to enforce a order on this?

Upvotes: 0

Views: 64

Answers (1)

Saif Ahmad
Saif Ahmad

Reputation: 1171

For your scenario, you can use the Template Method pattern.

Template method defines the steps to execute an algorithm and it can provide a default implementation that might be common for all or some of the subclasses

An Example below

public abstract class BaseClass {
    public final void doWork() {
        preConditionCheck();
        runMigration();
        postCondition();
    }

    protected abstract void preConditionCheck();
    protected abstract void runMigration();
    protected abstract void postCondition();
}

Usage:

public class MyClass extends BaseClass {
    protected void preConditionCheck() {
        // Set up resources or perform any necessary pre-processing
    }
    protected void runMigration() {
        // Perform the actual work here
    }
    protected void postCondition() {
        // Clean up resources or perform any necessary post-processing
    }
}

Upvotes: 2

Related Questions