模板方法这个名字看着很陌生,其实在游戏中大量地使用了模板方法,因为游戏中存在玩家、NPC和静态物体等不同的对象,使用多态特性能很好地进行区分。 模板方法的定义是:模板方法模式:在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。
举个最简单的玩家和NPC死亡时的逻辑:流程图如下:
The code is as follows//MVC.cpp: Defines the entry point of the console application. //#include "stdafx.h"#include <iostream>#include <string>#include <sstream>using namespace STD;classobject{ Public: Object (): M_dead (0) { }voidSetdead () {cout<<"========================="<<endl; Beforedead (); Ondead (); Afterdead ();cout<<"========================="<<endl; }Virtual voidBeforedead () {}Virtual voidAfterdead () {}voidOndead () {cout<<"Skill End"<<endl;cout<<"You are dead!"<<endl; }BOOLIsdead () {returnM_dead; }Private:BOOLM_dead;};classPlayer: Publicobject{ Public:Virtual voidBeforedead () {cout<<"Interrupt Trade If you are trading!"<<endl; }Virtual voidAfterdead () {cout<<"nothing!"<<endl; }};classNPC: Publicobject{ Public:Virtual voidBeforedead () {cout<<"Call Beforedead Lua script!"<<endl; }Virtual voidAfterdead () {cout<<"Call Afterdead Lua script!"<<endl; }};int_tmain (intARGC, _tchar* argv[]) {auto_ptr<Player> Player (NewPlayer ());auto_ptr<NPC> NPC (NewNPC ());cout<<"Player dead!"<<endl; Player->setdead ();cout<<"NPC dead!"<<endl; Npc->setdead ();}
The advantage of the template method is that the commonality is implemented in the parent class, and the differences are implemented in different subclasses.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The application of design pattern in game--template Method (vii)