首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

设计形式中迷宫的实现,用于学习创建型模式

2013-10-08 
设计模式中迷宫的实现,用于学习创建型模式设计模式一书相信不少人看过。其中创建型模式一节通过一个创建迷

设计模式中迷宫的实现,用于学习创建型模式

    设计模式一书相信不少人看过。其中创建型模式一节通过一个创建迷宫的例子阐述了工厂模式、抽象工厂模式等创建型模式。对于初学者而言,书中讲解并未实现具体代码,对于几种设计模式的优势不能深刻的体会。出于学习的目的我实现了这个迷宫,并且尽量保持原书中的类结构,用于体会创建型模式的优点。代码并不难,详见注释。本源码中仅实现了抽象工厂模式,其他模式详见设计模式一书。注意启动RTTI,下图为运行效果。

设计形式中迷宫的实现,用于学习创建型模式

    以下源码为不使用创建型模式的实现。

void MazeGame::CreateMaze(MazeFactory& factory){Maze* aMaze=factory.MakeMaze(2,5,Coor(0,0));Room* r1=factory.MakeRoom(Coor(0,0));Room* r2=factory.MakeRoom(Coor(0,1));Room* r3=factory.MakeRoom(Coor(0,2));Room* r4=factory.MakeRoom(Coor(0,3));Room* r5=factory.MakeRoom(Coor(0,4));Room* r6=factory.MakeRoom(Coor(1,0));Room* r7=factory.MakeRoom(Coor(1,1));Room* r8=factory.MakeRoom(Coor(1,2));Room* r9=factory.MakeRoom(Coor(1,3));Room* r10=factory.MakeRoom(Coor(1,4));Door* door1=factory.MakeDoor(r1,r2,true);Door* door2=factory.MakeDoor(r2,r3,true);Door* door3=factory.MakeDoor(r3,r4,false);Door* door4=factory.MakeDoor(r4,r5,true);Door* door10=factory.MakeDoor(r6,r7,true);Door* door11=factory.MakeDoor(r7,r8,true);Door* door12=factory.MakeDoor(r8,r9,true);Door* door13=factory.MakeDoor(r9,r10,false);Door* door5=factory.MakeDoor(r1,r6,false);Door* door6=factory.MakeDoor(r2,r7,true);Door* door7=factory.MakeDoor(r3,r8,false);Door* door8=factory.MakeDoor(r4,r9,true);Door* door9=factory.MakeDoor(r5,r10,true);aMaze->addRoom(r1,0,0);aMaze->addRoom(r2,0,1);aMaze->addRoom(r3,0,2);aMaze->addRoom(r4,0,3);aMaze->addRoom(r5,0,4);aMaze->addRoom(r6,1,0);aMaze->addRoom(r7,1,1);aMaze->addRoom(r8,1,2);        aMaze->addRoom(r9,1,3);aMaze->addRoom(r10,1,4);r1->SetSide(North,factory.MakeWall());r1->SetSide(South,door5);r1->SetSide(West,factory.MakeWall());r1->SetSide(East,door1);r2->SetSide(North,factory.MakeWall());r2->SetSide(South,door6);r2->SetSide(West,door1);r2->SetSide(East,door2);r3->SetSide(North,factory.MakeWall());r3->SetSide(South,door7);r3->SetSide(West,door2);r3->SetSide(East,door3);r4->SetSide(North,factory.MakeWall());r4->SetSide(South,door8);r4->SetSide(West,door3);r4->SetSide(East,door4);r5->SetSide(North,factory.MakeWall());r5->SetSide(South,door9);r5->SetSide(West,door4);r5->SetSide(East,factory.MakeWall());r6->SetSide(North,door5);r6->SetSide(South,factory.MakeWall());r6->SetSide(West,factory.MakeWall());r6->SetSide(East,door10);r7->SetSide(North,door6);r7->SetSide(South,factory.MakeWall());r7->SetSide(West,door10);r7->SetSide(East,door11);r8->SetSide(North,door7);r8->SetSide(South,factory.MakeWall());r8->SetSide(West,door11);r8->SetSide(East,door12);r9->SetSide(North,door8);r9->SetSide(South,factory.MakeWall());r9->SetSide(West,door12);r9->SetSide(East,door13);r10->SetSide(North,door9);r10->SetSide(South,factory.MakeWall());r10->SetSide(West,door13);r10->SetSide(East,factory.MakeWall());    m_maze=aMaze;}


热点排行