user13630431
user13630431

Reputation: 33

Can I create my own methods in a subclass using the template method design pattern?

Whether using methods created outside the abstract class will disturb the Template Method design pattern? Will it still be Template Method pattern if I create MyOwnMethod and call it inside a method?

public abstract class TemplateMethodClass {

    public final void TemplateMethod() {
      a();
      b();
      c();
    }

    protected abstract void a();

    protected abstract void b();

    protected abstract void c();
}
public class SubClass extends TemplateMethodClass {

    public void MyOwnMethod() {
        System.out.println("I am not from template");
    }

    @Override
    protected void a() {
        MyOwnMethod();
    }

    @Override
    protected void b() {}

    

    @Override
    protected void c() {}
}

Upvotes: 1

Views: 135

Answers (1)

Ori Marko
Ori Marko

Reputation: 58772

Template Method design pattern is about each subclass define certain steps in a skeleton

The intent is to define the skeleton of an algorithm by postponing some steps to subclasses i.e. it lets subclasses define certain steps of an algorithm in their own way keeping the structure of the algorithm intact.

Steps can have one or multiple methods inside them, and if those methods are used only in subclass they will probably be private

Upvotes: 1

Related Questions