模板模式

模板模式

C++ 方式:

Game.h

#include

class Game

{

protected:

virtual void initialize() = 0;

virtual void startPlay() = 0;

virtual void endPlay() = 0;

public:

virtual void play() {

initialize();

startPlay();

endPlay();

}

};

Cricket.h

#include "Game.h"

class Cricket :

public Game

{

protected:

virtual void initialize() {

std::cout << "Cricket Game Finished!" << std::endl;

}

virtual void startPlay() {

std::cout << "Cricket Game Initialized! Start playing." << std::endl;

}

virtual void endPlay() {

std::cout << "Cricket Game Started. Enjoy the game!" << std::endl;

}

};

Football.h

#include "Game.h"

class Football :

public Game

{

protected:

virtual void initialize() {

std::cout << "Football Game Finished!" << std::endl;

}

virtual void startPlay() {

std::cout << "Football Game Initialized! Start playing." << std::endl;

}

virtual void endPlay() {

std::cout << "Football Game Started. Enjoy the game!" << std::endl;

}

};

Main.cpp

#include

#include "Cricket.h"

#include "Football.h"

int main(int argc, char* argv[]) {

Game *game = new Cricket();

game->play();

std::cout << std::endl;

game = new Football();

game->play();

}chpeagle chpeagle

chp***le@126.com

5年前 (2020-08-17)

🎭 相关推荐 🎭

贴片钽电容封封装及规格和参数资料
365赢了不让提款

贴片钽电容封封装及规格和参数资料

📅 07-10 👀 5871
世界杯红牌大全:02和06世界杯喜提红牌球员盘点,国足有人上榜?
如何设置BIOS以更换系统硬盘(BIOS设置教程及关键步骤)