我试图弄清楚我是否正确理解了什么是模块化代码。我知道它非常强大/有用,所以我想确保自己学习正确。
为了开始学习,我制作了一个相当简单的系统,该系统根据一些条件将实体分组在一起。先到先得。
我还想以图形方式显示组及其成员,以向用户(我自己)显示发生了什么。我将为此使用SDL库。
因此,让我们将其分为几个类;
实体
主类“实体”将具有用于线程安全的Boost::mutex,以及一个包含指向实际实体的指针的映射。我们还提供一个函数,当提供实体ID时,该函数从所述映射中检索指向实际实体的指针。
class Entities
{
public:
boost::mutex access_entitymap; //Thread safety
std::map<unsigned int, Entity*> entitymap;
Entity* getEntity(unsigned int entityID);
};
实体
包含有关实际实体的信息,例如其唯一ID。以及指向父“实体”的指针。
LFDGroups
分组系统。
包括带有指向实际组的指针的 map ,
一张 map ,其中包含该组在队列中的位置(先到先服务。完整的组将从该 map 中删除,以加快迭代速度),
以及包含实体在组中位置的 map (5个地点,哪个实体占据了哪个地点?)。
此外,它还包括一些在所述 map 上操作的功能。例如添加和删除成员。例如,
addmember()
函数将确保将实体添加到具有最高优先级的组中,或者确保在必要时创建新组。组对象
包含有关实际组的信息,例如它的唯一ID和居民实体的ID。而且还具有一些功能,例如;
LFDGroups *lfdgroup; //Parent LFDGroups;
bool isEmpty(); //is this group empty?
bool isFull(); //is this group full?
unsigned int getPosition(); //Position in queue?
bool addMember(unsigned int entityID,bool snatchIt);
/*Add a member. Calls removeMember() on the entities' groupObject
first if the entityID is already in another group.*/
bool removeMember(unsigned int entityID,bool snatchIt);
/*Remove a member from this group, and snatch a member from another
group further up in the queue. This ensures groups are always full
if enough people are queued.*/
bool hasMember(unsigned int entityID); //Is this entity ID in our group?
/*etc. etc.*/
队列
提供一些易于使用的功能以使测试更加容易。如;
void addFakeEntity(bool queuenow); //Create an all new entity and immediately queue it.
void removeFakeEntity(); //Remove a random entity from a random group
void removeFakeEntity(unsigned int entityID); //Remove a given entity from it's corresponding group.
SDL主
以图形方式显示LFDGroups的组发生了什么。它有多少成员,哪些地点被拍摄,哪些不被拍摄,等等。
还证明了可以与Queue功能一起使用的按钮。如“添加”按钮将调用“queue-> addFakeEntity(true)”
因此,现在我可以轻松地开始整个过程了。
#include "SDL_main.h" //gfx
#include "class_LFDGroups.h" //group system
#include "queue.h" //ease of use for testing
#include "class_entities.h" //entities
int main( int argc, char* args[] )
{
Entities * entities = new Entities;
LFDGroups * lfdgroups = new LFDGroups(entities);
Queue * queue = new Queue(lfdgroups);
SDLMain * sdlmain = new SDLMain(queue);
return 1;
}
实体。毕竟,没有它就无法运行。
当然可以;
因此,这意味着即使我确实禁用了组的图形显示,我仍然可以将实际的分组系统用于其他用途。
而且,与某些对象有关的功能也位于该对象本身内。例如,
Entity* getEntity(unsigned int entityID);
函数在Entities
类中,而不在groupObject
中,即使这是目前唯一使用它的函数。这就是模块化编码吗?我做对了吗?
最佳答案
是的,您的程序希望遵循模块化的编程范例,例如将单独的组件组合在一起组成程序,并以可以替换特定组件的方式编写程序。
因此,您已将程序的逻辑拆分为单独的类,并且还将这些类拆分为单独的编译单元(假设是这样,基于SDLMain.h源代码中的包含内容),因此添加了一个新功能来表示您的小组类,只需要更改该模块(假设新功能仅由该类内部调用即可),并且从源头上看,该程序在逻辑上分为易于识别的独立部分。
您还可以轻松替换部分代码,例如GUI前端可以替换为Qt或wxwindows。由于gui调用数据的操作不会更改,因此可以编写新的gui代码,并调用同一组操作,并且数据组件也不会更改。
关于c++ - 模块化编码到底是什么,我做对了吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9003652/