Notifying a class of another class' changes - c++

Having the classes Container, Item and Property, the container shall be notified whenever a property in an item changes.
The container is the owner of the items and needs the information to properly manage them according to their properties.
I've thought of 2 options yet:
Observer pattern.
Proxy object.
The observer pattern seems to be too heavy for that task in my opinion. A proxy object could work out well, however in that case I'd violate the DRY principle, because I have to forward calls from the proxy to the actual object.
A requirement is that the details are hidden from the user. It's required that it's not needed to call some update_item() function or similar, i.e. giving the responsibility of informing the container to the user, which might lead to usage problems.

In such simple case I don't see a reason of using Observer. Since an Item can be only in one container at once I would just go with giving the Item a reference or pointer to the container it is placed in.
When some Property of the Item changes it as able to notify it's Container via that pointer
Observer pattern is useful in case you need to notify many objects.
EDIT
Making every simple thing using Interfaces and extremely clean design may also harm you. I think the quote from zen of Python explains good what i mean:
Special cases aren't special enough to break the rules. //make Interfaces
Although practicality beats purity. //but not everywhere
So you should a have balance between purity and practicality

You should use the pattern that is easiest to understand and maintain, and requires the least invention of specialized components. In the environment I work in (objective-C), the observer pattern is about as uncomplicated as it gets. It also offers flexibility when your notification requiements change.
Andrew's answer is event simpler - direct communication between objects does not requie the invention of a proxy or the overhead of notification handling. But it has less flexibility, should you need it in the future.
I'm not sure what "too heavy" means. Perhaps you can explain that.

As has been mentioned before, an Observer is pretty much overkill here, but the solution is pretty simple. You just need to "bubble up" the event.
When a property is changed, it notifies it's parent item.
When an item is changed (a side-affect from either a property changing, or something more integral to the item), it notifies it's container/parent).
When a container is notified, well, you're done. If containers can be nested then I guess it can raise an event to it's parent container if necessary.

Related

Observer with multiple subjects using std::unordered_set

I have seen implementations of the Observer design pattern in which the Observer is responsible for multiple Subjects. Most of these implementations use a std::vector<Subject*> in order to keep track of the Subjects.
Would it be possible for me to do a similar thing, using a std::unordered_set<weak_ptr<Subject>> instead?
The reason I want to use an unordered_set is that I will not need duplicates, and I don't need an ordered container. From what I understand, an unordered_set is the way to go in this situation. Also, the reason I am using a weak_ptr is that it should be safer?
If you disagree, leave an answer explaining what container I should use instead. If I did use the unordered_set, I would have to declare a hash function for the weak_ptr, but could this be accomplished by just using the hash function for the pointer inside, obtained with subjects.lock().get()?
First of all, in my answer I will use Subject as the one who sends messages to registered Observers, since it is the common use of this two terms.
Would it be possible for me to do a similar thing, using a std::unordered_set<weak_ptr<Observer>> instead?
It is possible. However remeber that the object held by a weak_ptr can be freed, weak_ptr needs to be casted to a shared_ptr before accessing the underlying object. It is done this way so the object is not freed while you are handling it.
Would it be possible for me to do a similar thing, using a std::unordered_set> instead?
If you need to enforce uniqueness the unordered_set looks like a good choice to me. If you don't need to, then a vector is more straightforward solution. Some would tell that unique_set is slower and requires more memory than a vector, but unless you need very high frequency registration of Observers or thousands of them, you won't notice the difference.
About the weak pointer, it gives you the flexibility of having your Observers deallocated while registered, so it should be fine. This behaviour may be unexpected if you come from a memory managed language like Java. If you want to hold them in existence while they are registered in your Subject you may use a shared_pointer instead.
I would have to declare a hash function for the weak_ptr, but could this be accomplished by just using the hash function for the pointer inside, obtained with observer.lock().get()?
Be careful when creating hash functions, I dont recommend you to use object's pointer for the hash function, specially if your Subjects can be copied/moved. Instead you may create an unique identifier for every Subject upon creation using a counter, and remember to write copy/move constructors and operators accordingly.
If you cannot write an identifying hash function, then you should't use the unique_set, since you lose the advantages it brings.
As a footnote, the beauty of object containers is that you can fit them to your needs, every solution is the correct solution if it does what you really want.
There isn't really one 'correct' answer for the choice of container; it depends upon what you are aiming for from the point of view of performance. And whether or not performance is really all that important for this.
It also depends upon memory efficiency. If you only have a few of these unordered_set objects and need very fast lookup then it may be a good choice. Since it is a hash table it will use a fairly large amount of memory per unordered_set object.
If you have a lot of unordered_set objects with fairly few items then it may get a bit expensive in terms of memory budget. If you need fast insertion and removal then std::set may be better in this case. However if the collection only ever contains a handful of items then the lookup will probably actually be faster with a linear search of std::vector due to the processor cache (i.e. better locality of reference of the vector elements compared to std::set - which may result in more elements being on the same cache line). Memory usage of vector will be lower than either of std::set or std::unordered_set.
If you need fast lookup of specific objects for some reason and use std::vector and typically have a a moderate number of elements then you could insert items into the vector in sorted order. You can then use std::lower_bound to do an O(log n) binary search lookup. However, this has a potentially high cost for inserting and removing elements.
I'd probably just go for std:vector in most cases - you generally have few observers, so may as well keep memory usage tighter.
And using weak_ptr is certainly a good option if these objects are used elsewhere with shared_ptr.
In the Observer pattern the Observer subscribes to notifications about changes on a Subject. The Subject is responsible for updating all subscribed Observers whenever its observable state changes. For that to work the Observers do not need to keep track of the Subjects. Instead the Subject must keep track of all subscribed Observers.
A nice explanation of the Observer pattern can be found here: https://sourcemaking.com/design_patterns/observer
Code outline:
class Subject;
class Observer
{
public:
// when notified about a change, the Observer
// knows which Subject changed, because of the parameter s
virtual void subjectChanged(Subject* s)=0;
};
class Subject
{
private:
int m_internalState;
std::set<Observer*> m_observers;
public:
void subscribe(Observer* o)
{
m_observers.insert(o);
}
void unsubscribe(Observer* o);
{
m_observers.erase(o);
}
void setInternalState(int state)
{
auto end=m_observers.end();
for(auto it=m_observers.begin(); it != end; ++it)
it->subjectChanged(this);
}
};
In most cases it won't matter which exact collection type you choose for storing the Observers, because there will be very few Observers. However, choosing a set-type has the advantage, that each Observer will receive only one notification. With a vector it could happen that the same Observer receives multiple notifications about the same change, if (for some reason) it was subscribed multiple times.
I really think that using std::unordered_set is a bit over-kill.
what is this observer pattern? when an event or a change of state occurs, iterate over an array of state-checkers and make them do something if the state is invalid or special in any sort.
this has being said, you want to iterate over an array with objects with overriden virtual function and call it. why whould set give us any benefit?
also, I don't get the weak_ptr idea - the owner of the observers is the array with holds them. the owner of that array is the Subject.
now that all has being said, I would go with std::vector<std::unique_ptr<Observer>>.
Edit:
using C++11, I'd even go with std::vector<std::function<void(Subject&)>> and avoid the boilerplate of inheriting+overriding.
The simplest thing to do is to roll with boost::signals2, which already implemented this for you, for all signatures. The fundamental problem with your approach is that the implementation is tied to a particular signature with a particular subject and observer, which is virtually worthless compared to a generic solution that applies for all cases.
The Observer pattern is not a pattern, it's a class template.

C++ pattern for multiple "worker classes" that manipulate a large data class

I have a single very large data class (really a struct, honestly), which needs to be manipulated in enough different ways that I don't just want to implement all of the manipulators as member methods of the data class.
Right now, I have the manipulators set up as singletons, or small instantiated classes held by some manager object, and I pass every manipulator a pointer to the data class during initialization. This works, but feels a little sloppy to me.
One complicating issue is that the manipulators have state. One example of manipulator state that could be factored out of the manipulators themselves is thread-safety helpers (mutexes/semaphores), but there are other data members that logically belong to the manipulators so I don't think this problem is going away.
So I'm wondering, is there some design pattern that can provide a cleaner solution for this situation?
A factory pattern could be used with the factory offering a method taking a pointer or reference to the data, and a value (possibly enumeration) indicating the operation to be performed, it then selects the agent that can perfrom that operation and asks it to do so.
As for the states, if the agents' states are synchronised then a single state in the factory would be fine - if they are not then the factory could simply provide a method to be called in the event that anything happens that could change any agent's state and inform all the agents. Or, the agents could themselves be observers of whatever it is that causes the state changes.
As for implementing a state machine - that's also often done using a factory pattern! So you could have a factory of factories where each sub factory is also an observer. This would be almost too awesome for words.

Memory Management Design

I am having some issues designing the memory management for an Entity-Component system and am having some issues coming up with the detail of the design. Here is what I am trying to do (note that all of these classes except Entity are actually virtual, so will have many different specific implementations):
The Program class will have a container of Entity's. The Program will loop through the Entity's and call update on each of them. It will also have a few SubSystem's, which it will also update on each loop through.
Each Entity will contain two types of Component's. All of them will be owned by a unique_ptr inside the Entity since their lifetime is directly tied to the entity. One type, UpdateableComponent, will be updated when the Entity.update() method is called. The second type SubSystemComponent will be updated from within their respective SubSystem.
Now here are my two problems. The first is that some of the Component's will control the lifetime of their parent Entity. My current idea for this is that Component will be able to call a function parent.die() which would change an internal flag inside Entity. Then after Program finishes looping through its updates, it loops through a second time and removes each Entity which was marked for deletion during the last update. I don't know if this is an efficient or smart way to go about it, although it should avoid the problem of an Entity dieing while its Component's are still updating.
The second issue is that I am not sure how to reference SubSystemComponent's from within SubSystem. Since they are refered to by a unique_ptr from inside Entity, I can't use a shared_ptr or a weak_ptr, and a standard pointer would end up dangling when the Entity owning a component dies. I could switch to a shared_ptr inside the Entity for these, then use a weak_ptr in the SubSystem's, however I would prefer to not do this because the whole point is that Entity completely owns its Component's.
So 2 things:
Can my first idea be improved upon in a meaningful way?
Is there an easy way to implement a weak_ptr sort of functionality with unique_ptr, or should I just switch to shared_ptr and just make sure to not create more than one shared_ptr to the SubSystemComponent's
Can my first idea be improved upon in a meaningful way?
Hard to say without knowing more about the nature of the work being undertaken. For example, you haven't said anything about your use of threads, but it seems your design gives equal priority to all the possible updates by cycling through things in a set sequence. For some things where low latency is important, or there's some useful prioritorisation that would ideally be done, a looping sequence like that isn't good, while other times it's ideal.
There are other ways to coordinate the Component-driven removal of Entities from the Program:
return codes could bubble up to the loop over entities, triggering an erase from the container of Entities,
an Observer pattern or lambda/std::function could allow the Program to specify cleanup behaviour.
Is there an easy way to implement a weak_ptr sort of functionality with unique_ptr,
No.
or should I just switch to shared_ptr and just make sure to not create more than one shared_ptr to the SubSystemComponent's
It sounds like a reasonable fit. You could even wrap a shared_ptr in a non-copyable class to avoid accidental mistakes.
Alternatively - as for Entity destruction above - you could coordinate the linkage between SubSystem and SubSystemComponent using events, so the SubSystemComponent destructor calls back to the SubSystem. An Observer pattern is one way to do this, a SubSystemComponent-side std::function fed a lambda is even more flexible. Either way, the Subsystem removes the SubSystemComponent from its records.

What's the best way to set 'deep' configuration options?

Assume there is a function that requires a configuration setting as an input, but this function is called several levels deep from the top-level 'main' function.
What's the best way, in terms of best programming practices, to pass this setting to the function?
One way is to just use a global variable and set that at the top level function and read it in the target function, but I assume that that is considered bad programming practice.
Another way is to pass the setting as an argument all the way from the top, through the several intermediate functions, all the way down to the final target function. This seems very tedious though and perhaps error-prone.
Are there other approaches?
You can use your language of choice for your answer, but FYI, I'm using C/C++, Perl, and Matlab.
I like singleton objects for configuration. It's a shared resource that should only ever have one instance. When you try to create a new object, you get the existing one. You don't worry about global variables or subroutine or method parameters. Simply get a new configuration object and use it as long as you need it.
There's an example in Gang of Four for C++.
Leave the procedural programming style with deep call stacks behind and the answer becomes a banality.
Remodel your program to take advantage of modern object-orientation. Perl roles make for flat hierarchies. A configuration is then just an attribute.
A system I work with uses a Publish-Subscribe (Observer Pattern) implementation to propagate settings/configuration changes to objects that need to know about them.
The object (Subscriber, or Observer in the original Gang of Four description) that needs to be notified of settings changes:
Inherits from Subscriber.
Attaches itself (subscribes) to the Publisher via the Publisher's Attach method.
Is notified by the Publisher whenever settings/configuration changes occur.
We use a variant that allows Subscribers to poll Publishers for settings/configuration data on demand.
Using the Publish-Subscribe pattern minimizes coupling between the object that manages the settings, and the objects that need them.
In matlab, I always have a script allParam.m, where I set all the parameters.
If a function needs one of those parameters, I just call the script, and it is set.

Calling timeconsuming functions from a constructor

What I'm looking right now is a set of classes derived from a common base class. Most, but not all, of the classes require some input parameters which are obtained through modal dialogs. Those dialogs are set up and executed in the constructor of the classes. As long as the dialog isn't finished, the object isn't constructed completely. What problems could arise by delaying the execution of a constructor?
I was thinking of replacing everything with a callback mechanism that is provided to the dialogs to set up the objects or using a factory to get usable objects right after construction. What other patterns are there to solve this situation?
No "problems" can arise as far as the language is concerned. The constructor is allowed to take as long as it likes.
Where it might be a problem is in the confusion it might cause. Will the programmer using the class be aware that the constructor blocks the thread for a long time?
Without knowing any details of your code, a callback or some other asynchronous mechanism might be better, to avoid blocking the thread.
What do these classes do? If they are not there just to manage the UI, you have a problem with separation of concerns... the user input gathering should be separated from classes that process that input.
I think it's a valid design choice. It does make sense to have a class called "UserInput" that will but be fully constructed after the user has provided input.
It also does induce a tight coupling to the data-entry method - interactive: you won't be able to use these classes with mockup data, for example.
So if you need the flexibility of the choice, do decouple data entry from business logic. If you want ready-to-use objects, go ahead asking the user for input at construction time.