Template Method Pattern

1,764 views

Published on

Template Method Pattern (TMA)

Published in: Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,764
On SlideShare
0
From Embeds
0
Number of Embeds
70
Actions
Shares
0
Downloads
47
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Template Method Pattern

  1. 1. Template Method Pattern High Level Algorithm Monis Iqbal Snr. Software Engineer Creative Chaos (pvt.) Limited
  2. 2. Definition <ul><li>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. <GOF> </li></ul>
  3. 3. <ul><li>Different implementations of algorithms leading to different algorithm altogether. (Similar code maintained differently) </li></ul><ul><li>Every class requires full knowledge of the algorithm. </li></ul><ul><li>Code duplication (Yuc!!) </li></ul>
  4. 4. <ul><li>Algorithm encapsulated in single class </li></ul><ul><li>Single control/entry point. </li></ul><ul><li>Subclasses only need to provide specialized algorithm details. </li></ul>
  5. 6. Primitive Methods <ul><li>Abstract class declares primitive methods leaving the subclasses to provide functionality. </li></ul><ul><li>Primitive methods used in Template Method . </li></ul><ul><li>Nicely documented and meaningfully named. </li></ul>
  6. 7. Concrete methods <ul><li>Used in Template method </li></ul><ul><li>Defined in abstract class </li></ul><ul><li>Declared final </li></ul>
  7. 8. Hooks <ul><li>Hook placed in the Template method. </li></ul><ul><li>Abstract class provides implementation. </li></ul><ul><li>Subclasses can “hook into” the algorithm if they want. </li></ul>
  8. 9. <ul><li>abstract class AbstractClass { </li></ul><ul><li>final void templateMethod() { </li></ul><ul><li>primitiveOperation1(); </li></ul><ul><li>primitiveOperation2(); </li></ul><ul><li>concreteOperation(); </li></ul><ul><li>if (hookIsTrue()) </li></ul><ul><li>hook(); </li></ul><ul><li>} </li></ul><ul><li>abstract void primitiveOperation1(); </li></ul><ul><li>abstract void primitiveOperation2(); </li></ul><ul><li>void final concreteOperation() { </li></ul><ul><li>… .. </li></ul><ul><li>} </li></ul><ul><li>boolean hookIsTrue() { return false; } </li></ul><ul><li>void hook() {} </li></ul><ul><li>} </li></ul>
  9. 10. Cache revisited <ul><li>Example by Code </li></ul><ul><ul><li>First in First Out (FIFO) Cache </li></ul></ul><ul><ul><li>Least Recently Used (LRU) Cache </li></ul></ul>
  10. 11. Intuition <ul><li>Encapsulation of Algorithm </li></ul><ul><li>Don’t call us, we’ll call you. (Hollywood Principle). </li></ul>
  11. 12. Questions ???

×