C++: Unsure about class - class manager relationship - c++

In my project I have a series of classes where their instances are manged by some manager class, for specific reasons.
Examples would be:
CSound - Abstracts a single sound
CSoundManager - Friend of CSound,
provides factory methods for creating
CSound instances, mixes active sounds
together
Also: CFont, CFontManager (for font access per-name), CSprite, CSpriteManager (for drawing each frame), and so on.
Here my first questions already:
Is what I'm doing a specific named design-pattern?
Is it in most cases, for whatever reason, a bad idea? If yes, why?
Then, I have asked myself:
How should the objects be created and destroyed? Should I permit creating them on the stack or directly with new, or only by the methods of the corresponding manager class?
(also for destruction: delete myFont; versus. FontManager.DestroyFont( myFont );)

Sounds like you may be violating the The Single Responsibility Principle (SRP) principle.
Is the CSoundManager class responsible for creating and managing the lifetime of CSound objects, or is it in charge of mixing active sounds together? Names can tell you much, and "Manager" can be understood in too many ways...
Generally, if you want these Manager classes to handle the lifetimes of your objects, then they should most likely be the only way to instantiate these objects (i.e. private ctors in the objects). See the Factory Design Pattern, although your implementation is a bit different.
If you do this, then the client code should never call new or delete. Manually calling delete is bug-prone, and should be avoided using idioms such as RAII. In this particular case, the Manager class should manage the lifetime of objects, and therefore delete will never appear in client code.

Looks like you are using some form of Factory design pattern. Not sure what makes you feel its a bad idea.
If you are treating Manager as container of the objects then it would control the life cycle of these objects. However if your objects need to live beyond the life of Manager then you would create them with new and Manager may not be responsible for destruction.

Generally what you're implementing is a Factory Method Pattern wherein an object allocates another object. However, you are not reaping the benefits of a Factory class as you're directly tying the allocated type to the factory as opposed to allowing the factory to manage all the internals abstractly. For instance, can you do this from any file, or just the factory for that resource type (CSoundManager): new CSound();
If so, you're missing the point and you basically just have a Singleton that allocates and manages an object. Consider abstracting your resource types. If CSound and CFont derived from IResource, you could have a CResourceManager that would just take an enum or some sort of identifier for that type and reduce coupling and dependencies in your codebase. Whenever you needed to use that object you could expose the type but more likely than not you could use an abstract manager (CResourceManager) to handle those objects using common interfaces (Update(), Create(), Destroy() etc...).
For your sound manager case, remember that sounds need only be loaded once and can be instanced with a unique state. In that right, have the resource manager manage the actual resource (CSound), and the sound manager (CSoundManager) maintain discrete instances (e.g. CSoundInstance) and manage mixing (via CSoundMixer). Specialize your classes in meaningful ways that manage complexity and reduce redundancy.
I used the sound manager as an example but this holds true for most io systems (graphics, input, physics).

Related

Singleton or passing pointers to static reference in manager

I have a connection manager which currently has a static reference to a class which is kept inside the connection manager in the private section of the class. A pointer to this class is passed to all connections and they can use it for utility purposes.
Now this class pointer is not immediately useful to the childs, but it is useful for the childs own children, so all that happens is that it's passed along.
Now I'm wondering that since there is only ever 1 instance of this utility class should I bother with all this passing around of the pointer, or would it be better to make the class a singleton and each class that requires it can simply use a static getInstance() method instead. This would mean that classes that don't care about it don't need to know about it.
There are lots of types of connections (30+) and none of them care about the utility class.
However, they will use classes (at the moment, just 2) that do care about the utility class.
I'm not sure if every type of connection should burden itself with something it doesn't care about, just for the sake of a couple of classes that it (may) use.
Singletons and static fields are generally considered evil. Why is it static anyway? It could happen so one day you'll need each connection manager to have its own reference.
The best idea I can think of is to make the reference non-static first. Then, forget about using the singletons. From this point you should start to think how to implement this in the most elegant way.
I don't know the nature of your class, but it sounds reasonable to me that each connection should have a reference (or a pointer) to the connection manager that manages it. Just in case.
Then, the connection manager should probably provide a getter for anyone who wants to access that utility class. Connections themselves should pass along either the reference to the connection manager or to the utility class depending on what makes more sense.
It also makes sense to pass the reference to the connection manager to the constructor of the common ancestor of the connections, if there is one (which it should be). This way, you no longer have 30+ classes that refer to something they don't really need, but just one abstract class that they are based upon.
And if you really want to do something singleton-like, then it's better to have a kind of static method with a parameter that returns the reference, as opposed to just a static method:
static UtilityClass *getInstance(int id);
// not static UtilityClass *getInstance();
Even if you don't use the id parameter right now, it may get very useful later, when you need multiple instances. You could have some sort of table or hash map that maps the id to the instance. You can even add a method that creates or replaces the instance for a specific id, which could be very useful for unit testing. Note that this approach still has at least the following disadvantages of the singleton pattern:
It is prone to various threading problems.
It still hides dependencies of your classes: that is, you can't say what a class uses just by looking at its API.
It is hard to give more advices without looking at the code.
If I understand you correctly, at the top layer there is a Connection Manager. It contains a static class which is useful later on.
The next layer down are many instances of a class which exists to service each of the connections managed by the aforementioned manager.
Each one of those may in turn use some instances of utility classes which would like access to information from the Connection Manager (in this case you've wrapped it up as the static object).
The question is how best should the 3rd layer down should gain access to the Connection Manager's contained information.
I'll call them: Manager (contains 'static class') -> Connection -> Utility
My suggestion would be to have the Connections take references to the Manager which owns them. They can't or shouldn't exist without it and they are managed by it. They in turn need to construct objects that need a specific bit of information from the Connection Manager (the static class contained within).
So when the Connection's construct the Utility classes, the Utility classes will require only the bit of information they need to operate (in this case a reference parameter for a class which happens to be static inside the Manager). They should take this by reference also. The Connection has the Manager class reference and is able to provide the constructor for the Utility the bit of information it needs to operate.
The reason I am suggesting this approach is:
Connections/Utility classes don't care whether the manager is a singleton (opens possibilities later if you need multiple managers)
Utility doesnt care whether static class is static. They only need a reference to a specific class they need.
Manager decides how it or its contained data needs to be allocated.
Lastly:
The only class which has reason to know about the other two main classes is the Connections class. It seems reasonable it might know which manager is managing it (and therefore some interface information). It also knows what the Utility classes it will require and what they will need in terms of construction params and other interface requirements.
To set this up there may be some funkiness with includes and classes may have to expose interfaces to each other but thats just standard fare anyway.
My 2c.
Singleton vs. Static
A good example of singleton usage: you wish only one instance to be running for a class, for example a texture manager, shader manager, connection pool manager etc. (see the pattern emerging:)
As an example lets take a connection pool manager: we want to create a single pool of connections that are managed and re-used by any other object that requires a connection in our code, so we make a ConnectionPoolManager singleton class, with say, 32 connections. This now allows every object requiring a connection to use a method, for example getFreeConnection, from the ConnectionPoolManager singleton, to retrieve a valid connection which can then be used as needed. This allows the ConnectionPoolManager to be the only part of the code anywhere that has anything to do with starting stopping and otherwise managing connections for your code.
Both singletons and static class can be implemented in such a way that they are thread-safe, however singletons have the advantage as they can implement interface (common), derive from other classes (less common), and a singleton can be passed around in exactly the same way as any other object (well a reference to it at least), where a static class can only implement static methods.
In regards of your specific case, you indicate that from 30+ classes only a couple require the utility class: the dependence on a singleton or static class is entirely up to your design and style. Should you wish a versatile way of doing it, with potential for change later, I would utilise a singleton. If you know that the static class will suffice and will not necessitate a redesign later, then go with that, or, if you have a particular liking for one or the other, use that one. There may also be hardware/software limitations and particulars which recommend one over the other, however that does not sound to be the case at the moment.
Let me know if you need more information, or if there are any particulars which you think may sway your choice one way or the other and I can provide information about pros and cons for each approach to suit your needs:)

about singleton

Well i read singleton are bad because they are anti pattern. I also read that the main reason for this is the global reference to singleton, anyway:
is it always possible to avoid singleton?
If so, lets says for example i got an IOCP network and i need to initialize it once and this object needs to be constant through the entire lifetime of the software. Same comes with a class i have called "paint" where i print data into the screen.
If i didn't make a singleton of it i would still need a global variable of the current Hwnd and to initialize the object locally each time i am going to use it (really annoying).
So using singleton is a sign my design is flaw?
What can i do to avoid them?
Thanks.
is it always possible to avoid singleton?
Yes, use a global variable, or (even better) fix your design. One option to fix a design is to use some kind of inversion of control.
If you try to use OO principles, you'll see you can do without a singleton.
Its a question of which entities need access to the resource that can only be instantiated once, and when (henceforth called the resource).
If the entities that need access to this resource can be instantiated with the resource (IOC, dependency injection), then that is the best way to go, thus keeping things simple and avoiding creating a Singleton. KISS.
If, for some reason, there are entities that need access to the resource, but cant be instantiated with it, then an alternative needs to be implemented. One option is a Singleton, but another option that I like to use is a Factory. This completely encapsulates the creation of the resource, and is much more future-proof, meaning that if in the future for some reason, more than one instance of the resource can be instantiated, then its all encapsulated. You cant/shouldnt try to do this with a Singleton. Of course, internally the factory will maintain the unique instance of the resource.
There are those that would argue that if an entity cant be instantiated with the resource, then the design is bad. That can be argued, and should probably be done so an a case-by-case basis.

Proxy pattern - Applicability & Examples

From here: http://www.oodesign.com/proxy-pattern.html
Applicability & Examples
The Proxy design pattern is applicable when there is a need to control
access to an Object, as well as when there is a need for a
sophisticated reference to an Object. Common Situations where the
proxy pattern is applicable are:
Virtual Proxies: delaying the creation and initialization of expensive
objects until needed, where the objects are created on demand (For
example creating the RealSubject object only when the doSomething
method is invoked).
Protection Proxies: where a proxy controls access to RealSubject
methods, by giving access to some objects while denying access to
others.
Smart References: providing a sophisticated access to certain objects
such as tracking the number of references to an object and denying
access if a certain number is reached, as well as loading an object
from database into memory on demand.
Well, can't Virtual Proxies be created by creating an individual function (other than the constructor) for a new object?
Can't Protection Proxies be created by simply making the function private, and letting only the derived classes get the accesses? OR through the friend class?
Can't Smart References be created by a static member variable which counts the number of objects created?
In which cases should the Proxy method be preferred on the access specifiers and inheritance?
What's the point that I am missing?
Your questions are a little bit abstract, and i'm not sure i can answer at all well, but here are my thoughts on each of them. Personally i dont agree that some of these things are the best designs for the job, but that isn't your question, and is a matter of opinion.
Virtual Proxies
I don't understand what you are trying to say here at all. The point of the pattern here is that you might have an object A that you know will take 100MB, and you don't know for sure that you will ever need to use this object.
To avoid allocating memory for this object until it is needed you create a dummy object B that implements the same interface as A, and if any of its methods are called B creates an instance of A, thus avoiding allocating memory until it is needed.
Protection Proxies
Here i think you have misunderstood the use of the pattern. The idea is to be able to dynamically control access to an object. For example you might want class A to be able to access class B's methods unless condition C is true. As i'm sure you can see this could not be achieved through the use of access specifiers.
Smart Referances
Here i think you misunderstand the need for smart pointers. As this is quite a complicated topic i will simply provide a link to a question about them: RAII and smart pointers in C++
If you have never programmed in a language like C where you manage your memory yourself then this might explain the confusion.
I hope this helps to answer some of your questions.
EDIT:
I didn't notice that this was tagged c++ so i assume you do in fact recognize the need to clean up dynamic memory. The single static reference count will only work if you only intend to ever have one instance of your object. If you create 2000 instances of an object, and then deleted 1999 of them none of them would have their memory freed until the last one left scope which is clearly not desirable (That is assuming you had kept track of the locations of all the allocated memory in order to be able to free it!).
EDIT 2:
Say you have a class as follows:
class A {
public:
static int refcount;
int* allocated_memory;
A() {
++refcount;
allocated_memory = new int[100000000];
}
~A() {
if(! --refcount) {
delete [] allocated_memory;
}
}
}
And some code that uses it:
int main() {
A problem_child; // After this line refcount == 1
while(true) {
A in_scope; // Here refcount == 2
} // We leave scope and refcount == 1.
// NOTE: in_scope.allocated_memory is not deleted
// and we now have no pointer to it. Leak!
return;
}
As you can see in the code refcount counts all references to all objects, and this results in a memory leak. I can explain further if you need, but this is really a seperate question in its own right.
I am no expert, but here are my thoughts on Virtual Proxies : If we control the initialization via a separate function say bool Create(); then the responsibility and control of Initialization lies with the client of the class. With virtual proxies , the goal is to retain creation control within the class, without client being aware of that.
Protection Proxies: The Subject being protected might have different kinds of clients, ones which need to get unprotected/unrestricted access to all Subject methods and the others which should be allowed access to a subset of methods hence need for Protection proxy.
A proxy is an object behaving as a different object to add some control/behavior. A smart pointer is a good example: it accesses the object as if you would use a raw pointer, but it also controls the lifetime of that object.
It's good to question whether there are alternatives to standard solutions to problems. Design Patterns represent solutions that have worked for many folks and have the advantage that there's a good chance that an experienced programmer coming to the code will recognize the pattern and so find maintaining the code easier. However, all designs represent trade-offs and patterns have costs. So you are right to challenge the use of patterns and consider alternatives.
In many cases design is not just about making code work, but considering how it is structured. Which piece of code "knows" what. You proposal for an alternative for Virtual Prozy moves (as fizzbuzz says) knowledge of creation from the proxy to the client - the client has to "know" to call Create() and so is aware of the life-cycle of the class. Whereas with the proxy he just makes an object that he treats as the worker, then invisibly creation happens when the proxy decides it makes sense. This refactoring of responsibility into the proxy is found to valuable, it allows us in the future to change those life-cycle rules without changing any clients.
Protection proxy: your proposal requires that clients have an inheritance relationship so that they can use protected methods. Generally speaking that couples client and worker too tightly, so we introduce a proxy.
Smart reference: no, a single static count is no good. You need to count references to individual instances.
If you carefully work through each case you will find there are merits to the design patterns. If you try to implement an alternative you start with some code that sems simpler that the design pattern and then discover that as you start to refactor and improve the code, removing deuplicationand so on you end up reinventing the design pattern - and that's a really nice outcome.

C++: What is the proper way of organising a programs subsystems?

Imagine you have a large application project, the code is split into a range of subsystems implemented as classes derived from CBaseSubsystem.
Here already comes my first question:
Is it a good idea to organize subsystems as classes [derived from a base class]?
Then, you have your subsystem classes. Now, you will need create have instances of them somewhere. But where?
Is it a good idea to have every subsystem instance stored in a global variable, for example:
extern CEventSystem* g_EventSystem;
Where should the instances be actually created? All together in a main()-like function?
Or is it better to avoid global variables entirely and organize the instances in a CSubsystemManager class or the like?
Would using singleton classes be an appropriate approach?
Very similar to this. I'd avoid Singleton, because it is absolutely unnecessary here and brings about many other issues.
Create the instances in a main-like routine. If something needs a system, provide access to it through some means, be it a parameter passed directly to that something or a container that provides access to these systems (IE: CSubSystemManager). You likely don't need to go so far as to write CSubSystemManager.
Avoid global state, there's a reason it has a stigma.
If you need a way to access an instance of each subsystem, I would avoid using "extern" and instead go with a singleton that gives you access to an instance of CSubsystemManager. The manager itself can take care of instantiating and managing your subsystem objects.
If you want to talk theory rather than provide a concrete question then consider designing in terms of a combination of Factory and Singleton with the possibility of Strategy in subsystems which may implement a similar operation for a range of different object types.
The main subsystem Factory is itself a singleton whose purpose is I hope obvious. Use lazy evaluation to allow only required subsystem objects to be loaded as needed. You may want to consider providing each subsystem with a reference counting mechanism which will allow them to be dropped when no longer needed. Some subsystems may themselves be singletons and/or may also implement Strategy pattern to provide a particular service for a range of class types.
This service may be for example validation, rendering, serialisation etc.
The value judgement of whether it is a "good idea" to build your application in this way is not for me to say. I would rather let older wisdom speak to that.
My solution would create a combo of a 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.)

Maintaining a std::set<boost::shared_ptr>

I'm writing a game and an accompanying engine in C++. The engine relies heavily on automation using a simple embedded scripting language. Scripts can create object classes, define event listeners on them, and produce instances from them. At present, an instance must be bound to a script-global identifier in order to preserve its existence. The obvious result of this is that there can be no anonymous objects, which will be by far the most common.
At present, instances are managed using a std::set<Instance*, spatial_sort>, where spatial_sort is a functor that sorts instances by position, for rendering and collision detection. Instances are removed and re-inserted each frame using their current position as a hint, under the assumption that they're not likely to move a whole lot in a fiftieth of a second. If a dead flag is set in the instance, it is erased from the set. The Instance constructors and destructor invoke insert(this) and erase(this), respectively.
In order to allow anonymous instances, I want to change the set to a std::set<boost::shared_ptr<Instance>, spatial_sort>, which would allow Instance to share ownership of instances and preserve their existence until they destroy themselves. Unfortunately, because the calls to insert() need to be placed in the constructor, shared_from_this() won't work for obtaining a shared_ptr to the Instance. It doesn't matter at all that Instance happens to already inherit from boost::enable_shared_from_this<> via its base class.
Can anyone recommend a suitable workaround?
Edit:
I did what I should have been doing in the first place, and split the behaviour of the Instance class into two classes: Instance and Reference. The expression new SomeClass in a script then returns a Reference to a new Instance. The Instance objects themselves are never managed using a shared_ptr, so they are responsible for committing suicide in response to a suitable event, e.g., end of animation, end of level, etc.
Thanks for the help! Refactoring is as good a solution as any if it Just Works.
You could add a static method to Instance that you then use to create new objects and that also does the administrative stuff like adding it to the set:
static Instance* create(int something) {
boost::shared_ptr<Instance> sptr(new Instance(something));
instanceset.insert(sptr);
return sptr.get();
}
If you want to make this the only way to construct an object of this class you could also make the normal constructor private or protected.
For more on this see also the C++ FAQ Lite entry about "Dynamic binding during initialization", which is not directly related but uses the same technique to work around the restrictions on the use of virtual functions in constructors.