Software

Template Method Pattern

This is behavioral design pattern, which means it focus on ways that individual objects collaborate to achieve a common goal.

The Template Method can be helpful if you have 2 classes with similar functionality, which apply generalization principle.

This UML diagram has the essential components: a public template method and abstract methods in the superclass. These abstract methods are implemented in the subclasses. There is also one step common to all: reachDestination. It is private because only the method in the superclass needs to access it.

Template Method Class Diagram.png

Step 1: Write a base abstract class.

public abstract class SelfDrivingVehicle {
    public sealed void DriveToDestination(){
        Accelerate();
        Brake();
        Steer();
        Accelerate();
        Brake();
        reachDestination();
    }

    protected abstract void Steer();
    protected abstract void Accelerate();
    protected abstract void Brake();

    private void reachDestination(){
        Console.WriteLIne("Destintion reached");
    }
}

Step 2: implement subclasses

public class SelfDrivingCar: SelfDrivingVehicle {
    protected void Steer(){
        Console.WriteLine("Car Steering API");
    }

    protected void Accelerate(){
        Console.WriteLine("Car Accelerate API");
    }

    protected void Brake(){
        Console.WriteLine("Car Brake API");
    }
}

public class SelfDrivingMotorcycle: SelfDrivingVehicle {
    protected void Steer(){
        Console.WriteLine("SelfDrivingMotorcycle Steering API");
    }

    protected void Accelerate(){
        Console.WriteLine("SelfDrivingMotorcycle Accelerate API");
    }

    protected void Brake(){
        Console.WriteLine("SelfDrivingMotorcycle Brake API");
    }
}

One thought on “Template Method Pattern

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.