Template method pattern: Difference between revisions

Content deleted Content added
Examples: use C++14 version of Design pattern book Sample Code implementation
PHP example: Move PHP example to Wikibooks
Line 40:
 
The Template pattern provides a solution. If the generated code follows the template method pattern, the generated code will all be an abstract superclass. Provided that hand-written customizations are confined to a subclass, the code generator can be run again without risk of over-writing these modifications. When used with code generation, this pattern is sometimes referred to as the [[Generation gap (pattern)|generation gap pattern]].<ref>{{cite book|last1=Vlissides|first1=John|title=Pattern Hatching: Design Patterns Applied|date=1998-06-22|publisher=Addison-Wesley Professional|isbn=978-0201432930|pages=85–101|url=http://www.informit.com/store/pattern-hatching-design-patterns-applied-9780201432930}}</ref>
 
==PHP example==
<syntaxhighlight lang="php">
abstract class Game
{
abstract protected void initialize();
abstract protected void startPlay();
abstract protected void endPlay();
 
/** Template method */
public final void play()
{
/** Primitive */
initialize();
 
/** Primitive */
startPlay();
 
/** Primitive */
endPlay();
}
}
 
class Mario extends Game
{
protected void initialize()
{
echo "Mario Game Initialized! Start playing.", PHP_EOL;
}
 
protected void startPlay()
{
echo "Mario Game Started. Enjoy the game!", PHP_EOL;
}
 
protected void endPlay()
{
echo "Mario Game Finished!", PHP_EOL;
}
}
 
class Tankfight extends Game
{
protected void initialize()
{
echo "Tankfight Game Initialized! Start playing.", PHP_EOL;
}
 
protected void startPlay()
{
echo "Tankfight Game Started. Enjoy the game!", PHP_EOL;
}
 
protected void endPlay()
{
echo "Tankfight Game Finished!", PHP_EOL;
}
}
 
$game = new Tankfight();
$game->play();
 
$game = new Mario();
$game->play();
</syntaxhighlight>
 
==C++ example==