Skip to main content

Template Pattern

Template Pattern 


Gamma Categorization: Behavioral Design Pattern
Summary:  Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

Sample Code

Problem: We want to have a digital camera template, which should be used or overriden by it's concrete classes.

Code

public abstract class DigitalCamera
{
    public void TakePhoto()
    {
        System.Console.WriteLine("Taking photo.");
    }

    public abstract void LiveView();

    public virtual void FireFlash()
    {
        System.Console.WriteLine("Firing flash.");
    }
}

public class Canon6D : DigitalCamera
{
    public override void LiveView()
    {
        System.Console.WriteLine("Using LiveView on a 1040kdots LCD.");
    }

    public override void FireFlash()
    {
        System.Console.WriteLine("No flash available.");
    }
}

public class Canon450D : DigitalCamera 
{
    public override void LiveView()
    {
        System.Console.WriteLine("Using LiveView on a 230kdots LCD.");
    }
}

Usage

var canon6D = new Canon6D();
canon6D.LiveView();
canon6D.FireFlash();
canon6D.TakePhoto();

var canon450D = new Canon450D();
canon450D.LiveView();
canon450D.FireFlash();
canon450D.TakePhoto();

Output

Using LiveView on a 1040kdots LCD.
No flash available.
Taking photo.
Using LiveView on a 230kdots LCD.
Firing flash.
Taking photo.

Comments