Quantcast
Channel: Free practice test , mock test, driving test, interview questions » design patterns
Viewing all articles
Browse latest Browse all 10

Template Method Design Pattern

$
0
0

Template Method Design Pattern

Problem

It is often tedious to implement many subclasses of a particular base class. It would be nice if there were a way to reference the existing structure, and only redefine some aspects of a class definition to make a new subclass.

Solution

A template is a very useful tool. It provides a way to replicate a base class in a sub class and only change what you want to without having to enter a lot of redundant code. When you use a template, you pass in parameters that configure your subclass to match you needs, without requiring you to completely define the new subclass. If you have ever used STL, then you are familiar with templates. STL has many predefined templates that can be used to make many useful subclasses. For example, in STL for C++ there is a template called list. You can make a list of floating point numbers with the line std::list<float>. This is quite a lot less trouble than creating your own implementation of a list class.

Consequences

To appropriately use a template, you must understand which methods can be overridden, and which methods must be overridden.

A template can provide a very efficient means of code reuse. If you can express your common functionality in a general way such that it can be templatized, then you have already increased code reuse.


Viewing all articles
Browse latest Browse all 10

Trending Articles