Spring Semester, 1998
Template Method

To Lecture Notes Index

### Contents of Doc 9, Template Method

 Template Method slide # 1

References

Design Patterns: Elements of Resuable Object-Oriented Software, Gamma, Helm, Johnson, Vlissides, Addison-Wesley, 1995, pp 325-330

`Doc 9, Template Method Slide # 2`

# Template Method

## Intent

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

Template methods tend to call:
concrete operations
concrete AbstractClass operations
primitive operations - must be overridden
factory methods
hook operations - can be overridden

It is important to denote:
which methods must overridden
which methods can be overridden
which methods can not be overridden
`Doc 9, Template Method Slide # 3`
Polymorphism
```class Account {
public:
void virtual Transaction(float amount)
{ balance += amount;}
Account(char* customerName, float InitialDeposit = 0);
protected:
char* name;
float balance;
}

class JuniorAccount : public Account {
public:     void Transaction(float amount) {//  put code here}
}

class SavingsAccount : public Account {
public:     void Transaction(float amount) {//  put code here}
}

Account* createNewAccount()
{
// code to query customer and determine what type of
// account to create
};

main()
{
Account*  customer;
customer = createNewAccount();
customer->Transaction(amount);```

}
`Doc 9, Template Method Slide # 4`
Deferred Methods

```class Account {
public:
void virtual Transaction() = 0;
}

class JuniorAccount : public Account {
public
void Transaction() { put code here}
}
```

`Doc 9, Template Method Slide # 5`
Template Methods

```class Account {
public:
void Transaction(float amount);
void virtual TransactionSubpartA();
void virtual TransactionSubpartB();
void virtual TransactionSubpartC();
}

void Account::Transaction(float amount)  {
TransactionSubpartA();
TransactionSubpartB();
TransactionSubpartC();          // EvenMoreCode;
}

class JuniorAccount : public Account {
public:          void virtual TransactionSubpartA(); }

class SavingsAccount : public Account {
public:          void virtual TransactionSubpartC(); }

Account*  customer;
customer = createNewAccount();
customer->Transaction(amount);```

`Doc 9, Template Method Slide # 6`
Polymorphism
The Good

Making modifications to program require:

Changing code that creates objects

```Account*  customer;
customer = createNewAccount();
customer->Transaction(amount);
```

`Doc 9, Template Method Slide # 7`
Polymorphism