Oberserver and Observable implemented by the same class - oop

Is it a good OO practice to implement Observer and Observable interface to the same class in cases like given below?
"News server application that notified if there are new news items. Then the subscribers of news categories get notified via the server when that happens"

It sounds like you are implementing the Composite pattern. You have a Composite Observer that receives events and then emits them to its children. Combining the Observer and Composite patterns is perfectly acceptable.

Related

Observer pattern: case of multiple registration of the same instance

I'm studying the observer, a kind of design pattern.
The observable object contains a list of observers. A list can accept redundant an observer instance. So we can limit this redundancy using a hash set instead of a list.
My question is, if we allow redundant registration of the same observer instance, is there any example that the observer is registered more than one time? Why the same observer is registered to the same observable multiple times?
One observable may produce several different types of event notifications. One observer may be interested in registering for a number of these notifications. Obviously you could design this scenario in different ways; but one way is to maintain all registrations in a single list.
The GoF does mention on page 296,
It's up to the observer to handle or ignore a notification.
This implies an observer needs to be aware of any potential for redundancy and react appropriately.

Observer pattern - Does observable needs to be always abstract?

I am new to design patterns , I am learning Observer pattern for that I went to many sites ,where I found the below UML diagram
So my question is on the UML or class design.If the purpose of the observer pattern is to notify the observers about the change in state of subject/object, Why the subject needs to be abstract can’t it be a ConcreteSubject directly as shown below:
What are the disadvantages or violations if we create a Subject as ConcreteSubject.
I understand that the purpose of defining the abstract subject class is to provide a base implementation of the properties and methods needed for the Observers to subscribe and receive notifications.
A more generic alternative would be to provide an interface. Or perhaps the abstract class is in fact implementing a more generic interface that only defines the methods that have to be implemented.
In other words the advantage of providing an interface is that you don't need to know the class that implements it.
The advantage of using an abstract class is that you have a base implementation of the methods needed to add or remove observers and to send them notifications. And you take advantage of this by deriving the class.
Making Concrete Observer dependent upon Concrete subject will solve one problem [Type casting in update method as update(ConcreteSubject cs)] but at the cost of generic nature of Pattern.
Concrete Subject and Abstract Subject (Observable) have clear demarcation of responsibilities namely - Implement Business logic and be an Observable across application and take care of Observers.
In case we avoid using Subject, every business class requiring Observers (May be added down the line) will have to repeat the code of Subject. (Extending one Concrete Subject from Another Concrete Subject is OO violation).
Best way will be to use Abstract Subject and keep extensions and code reuse open.

Object models in flux / redux

So i am learning the flux pattern using redux as a framework for it, to generate a mobile application in react-native (no backend).I feel I have been fighting against the pattern for some time due I come from an OO background and was expecting my model to be abstracted and bind somewhere in the pattern.
Last night I think I had an epiphany by thinking that this pattern enforces the idea that all is data and how is treated in reaction to events. So is fully functional programming and no abstractions (that have state) have a place inside this pattern.
So just to map to an OO world I have explain it in this mode to my brain:
internal objects in the store: each is equivalent to the properties of a class.
Event: equivalent to the reaction to something that happen and calls methods from a class.
reducer: the methods that transform the data inside a class.
views: the representation to the user of those abstractions.
My questions then are:
Is this weird theory (models inside the store). valid or just a bad idea?
if not valid, where do my models hook in a redux based application?
if not valid, this means this pattern is just to use on the front-end?

Notifying observers from nested structures

Currently, I am trying to dissect some tight coupling between the data model and the UI in an application by introducing the MVC pattern. Basically, this means making the model aware of the associated views in order to have them informed whenever properties inside the model change.
The data model is represented by a nested structure:
Model
- Node
- Leaf
- Leaf
- Node
- Leaf
Each element inherits from a common abstract base class (StructuredNode).
The problem I've been thinking about is: observers should be able to subscribe to the Model (and only the Model), but each element should be able to emit change notifications. This could be achieved in two ways - either notifications are routed up the hierarchy until they reach the Model, where they get pushed to the observers, or by implementing notifications in the base class, with a static observers list, as in this example:
public abstract class Base {
private static Map<IObserver> observers;
protected synchronized void internalSubscribe(final IObserver observer) {
observers.add(observer);
}
protected synchronized void notifyObservers(final Base obj) {
for (IObserver observer : observers)
observer.changed(obj);
}
// .. other base class operations
}
In this implementation, only Model would offer a public subscribe method, which internally would delegate to the protected internalSubscribe method of the base class. At the same time, each derivative of the base class could send a change notification, like this:
// Perform some operations that change the object's internal state
// ...
// Then notify all observers
notifyObservers(this);
Is this rather good or rather bad practice (using a static observers list)? Any opinions on this? Are there alternative solutions?
A static observer list is not a common solution, and I would not consider it a good practice for a generic use model.
Observers would be notified of changes to models they are not interested in. This means that all the burden of identifying the model firing the notification falls on the observers, which probably have no good and efficient way of doing it other than going up the hierarchy and finding the root node... a lot of code, that must potentially be implemented several times in several observers. In the end it would be simpler for the observer to ignore considerations and just update or recalc, even when the updated model is not the one it's interested in.
Of course all this may not apply in your case. If you know you will not have more than one model of this class in your application, then you can very well go with this solution.
Anyway, the requirement of having only the Model with a public subscribe method should not constrain you to using a static observer container to share among all Model instances. As you said, there is another way. Routing the notifications up the hierarchy is IMHO the correct way to go.
If you want to avoid routing, then you could choose to have the nodes keep a reference to their model. This may be more efficient if you know the tree structure will be deep an not very dynamic. If nodes can be moved from one Model to another, than this is a bit risky and requires some further code to keep the reference updated.

Observer pattern or Callback?

I have to do a design of a DownloadManager, but my main question is related to the notifications that a Download can send to the DownloadManager like onUpdate() to update a progress bar, onError(), onFinish(), etc. Somehow the DownloadManager has to receive this notifications from its Downloads.
I've thought 2 possible ways:
Observer pattern
Callbacks
Observer pattern
Basically there are 1 Observable and N Observers. In my case the DownloadManager has te be an Observer and the Downloads the Observables, so the relation is N Observables 1 Observer, just the opposite.
The advantage is to centralize all the possible notifications in one method, the notify() or update() (from java) method from the Observers, in my case only the DownloadManager. I can pass a param to the notify() method with the code of the notification.
Disadvantage? I'm using an oop pattern for a thing that can be done easily with a callback. Also, N observables 1 observer it's something weird, at least with the observer pattern because this pattern was done for 1 observable N observers, so I really won't be using the observer pattern.
Callback
Very similar to the observer pattern. The DownloadManager implements a "listener" (interface). This listener implements the notification functions onFinish(), onUpdate(), etc. Then this listener must be registered in all Downloads, so when a Download finishes it will call listener.onFinish(). Additionally I can pass parameters to this methods from the Downloads, like in the observer pattern.
Advantage: Easily usage.
Disadvantage: None.
I will probably use a callback because in my opinion it makes no sense to use an observer pattern for 1 observer N observables.
And you, which option will use?
Callbacks FTW. It is simpler, and in the vast majority of cases, simplicity influences every other aspect of the project in a positive way, including development, debugging, optimization, documentation and further maintenance.
The observer is more flexible/scalable. Is not that weird after all the usage you mentioned for the observer pattern. Patters are after all just guidlines, if you need to change it a bit to fit your needs then go for it.
Consider the case when you have multiple DownloadManagers (maybe this is not a valid use case for your particular situation). You will need to register both of them. If you have even more then you will have to register all of them. Pretty long list, plus you need to implement listeners management in the Downloads
There is also one option, which is opposite to Observer/Callback approach. You can turn clients of DownloadManager from passive to active players of the show. Instead of waiting for a message from the manager they will regularly request its status.
This way your download process will look much smoother to the end-user. And you will be able to control it better.
Of course, you will have to use two threads. Or you will have to teach the DownloadManager to work in small steps, returning control to its client, instead of running one unbreakable piece of work.
observer is more suitable because Manager need to send request to many instances.
It is easy to implement. In implementation point of it will be more scalable in terms of progress bar functionality and how much downloaded each one and Total % Download