Design Patterns
  • Introduction
  • Proto-Pattern
  • Anti-pattern
  • OO Design Principles
  • Classification
  • Creational Design Patterns
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Prototype
  • Structural design patterns
    • Adapter
    • Bridge
    • Composite
    • Decorator
    • Facade
    • Flyweight
    • Proxy
  • Behavioural Design Pattern
    • Chain of Responsibility
    • Command
    • Interpreter
    • Iterator
    • Mediator
    • Memento
    • Observer
    • State
    • Strategy
    • Template Method
    • Visitor
  • Concurrency Design Pattern
  • Architectural Design Pattern
  • Modern Desing Patterns
Powered by GitBook
On this page

Was this helpful?

  1. Behavioural Design Pattern

Template Method

Defer the exact steps of an algorithm to a subclass.

  • Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

  • The Template Method pattern provides an outline of a series of steps for an algorithm.

  • Objects that implement these steps retain the original structure of the algorithm but have the option to redefine or adjust certain steps.

  • This pattern is designed to offer extensibility to the client developer.

  • Template Methods are frequently used in general purpose frameworks or libraries that will be used by other developer.

EX:
var datastore = {
    process: function() {
        this.connect();
        this.select();
        this.disconnect();
        return true;
    }
};
 
function inherit(proto) {
    var F = function() { };
    F.prototype = proto;
    return new F();
}

function run() {
    var mySql = inherit(datastore); 
    // implement template steps 
    mySql.connect = function() {
        console.log("MySQL: connect step");
    }; 
    mySql.select = function() {
        console.log("MySQL: select step");
    }; 
    mySql.disconnect = function() {
        console.log("MySQL: disconnect step");
    }; 
    mySql.process();
}

run();
// MySQL: connect step
// MySQL: select step
// MySQL: disconnect step
PreviousStrategyNextVisitor

Last updated 5 years ago

Was this helpful?