The application of design pattern in game--template Method (vii)

Source: Internet
Author: User

模板方法这个名字看着很陌生,其实在游戏中大量地使用了模板方法,因为游戏中存在玩家、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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.