C ++: What is the correct way to organize program subsystems?

Imagine that you have a large application project, the code is divided into a number of subsystems implemented as classes derived from CBaseSubsystem.

Here my first question already comes:

  • Is it good to organize subsystems as classes [derivatives of a base class]?

Then you have subsystem classes. Now you need to create instances somewhere. But where?

  • Is it good that each instance of the subsystem is stored in a global variable, for example:
    extern CEventSystem* g_EventSystem;

  • Where should instances be created? All together in main () - a similar function?

  • Or is it better to completely eliminate global variables and organize instances in a class CSubsystemManageror the like?

  • Would using singleton classes be the right approach?

+3
source share
4 answers

Very similar to this one . I would avoid Singleton because there is absolutely no need here and causes many other problems .

Create instances in the main program. If something needs a system, provide access to it in some way, be it a parameter passed directly to this or the container that provides access to these systems (IE: CSubSystemManager). You probably don't need to go that far to write the CSubSystemManager.

Avoid the global state; there is a reason that it has stigma.

+1
source

, "extern" , CSubsystemManager. .

0

, , Factory Singleton Strategy , .

Factory , , , . , . , , , . / . , , , , ..

, " " , . , .

0

My solution will create combo singleton registry, AbstractFactory and Factory.

//in base module

class ISubsystem{} //an interface for a subsystem

//in module code
Registry::instance()->registerFactory("subsystem1",new Subsystem1Factory());

//in user code
IFactory* factory = Registry::instance()->getFactory("subsystem1");
ISubsystem* subsystem = factory->createObject(...); //you can implement whatever policy in factory impl. (like singleton etc.)
0
source

Source: https://habr.com/ru/post/1795595/


All Articles