Design Patterns- Multiple Observer - java

I am new to design patterns. I am writing a piece of code where there is one subject and multiple observers. Both subject and observers have interfaces. So say if I have 5 observers, do I need to create 5 different interfaces with their separate update methods? Or should I create just one interface and write five update methods for all observers?

Often you will need just one observer interface that all 5 observer classes can implement. What will differ will be how the observers react to the notification of change. Whether this applies to you will depend completely on your program structure and needs.
Note that observers that share a single interface can also listen for different changes in the observed, but still use the same interface. For example if you used a PropertyChangeListener as your observer interface, you could base what you listen to by checking the propertyName returned in the PropertyChangeEvent that is passed to your observer.
Note however that if what the observers are listening to are very different, then yes, they might need a unique interface. Using a Swing example, since that is what I'm most knowledgeable in, there are many different listener classes and interfaces available, including ActionListener, MouseListener, MouseMotionListener, ... all though derived from a common super interface, EventListener. Note that all pass a parameter to their listeners that is based on a common super class, the AWTEvent class.
For better more specific help, please consider giving us more specifics of your problem.

do I need to create 5 different interface with their seperate update methods? Or I should just create one interface and write five update methods for all observers?
One interface with five update methods seems much less cohesive than five different interfaces. However, you say you only have one kind of subject (which is the client to the Observers). But it depends on how cohesive is this client.
The interface segregation principle likely applies here to help you decide. If you provide more details, I could give more opinions.

IF you are using Java EE, I would suggest using topics and subscribers using JMS... It is more robust. I don't know what kind of solution you are looking for but it would be more robust if you need to persist and prevent from losing data...
Don't hesitate if you need something.

Related

Pluggable Adapter as mentioned in the GOF

The related Posts on Stackover flow for this topic :
Post_1 and Post_2
Above posts are good but still I could not get answer to my confusion, hence I am putting it as a new post here.
MY Questions based on the GOF's Elements of Reusable Object-Oriented Software book content about Pluggable Adapters (mentioned after questions below), hence I would appreciate if the discussions/answers/comments are more focused on the existing examples from GOF regarding the pluggable Adapters rather than other examples
Q1) What do we mean by built-in interface adaptation ?
Q2) How is Pluggable Interface special as compared to usual Adapters ? Usual Adapters also adapt one interface to another.
Q3) Even in the both the use cases, we see both the methods of the Extracted "Narrow Interface" GetChildren(Node) and CreateGraphicNode(Node)depending on Node. Node is an internal to Toolkit. Is Node same as GraphicNode and is the parameter passed in CreateGraphicNode only for populating the states like (name, parentID, etc) of an already created Node object ?
As per the GOF (I have marked few words/sentences as bold to emphasis the content related to my Questions)
ObjectWorks\Smalltalk [Par90] uses the term
pluggable adapter to describe classes with built-in interface adaptation.
Consider a TreeDisplay widget that can display tree structures graphically.
If this were a special-purpose widget for use in just one application, then
we might require the objects that it displays to have a specific interface;
that is, all must descend from a Tree abstract class. But if we wanted to
make TreeDisplay more reusable (say we wanted to make it part of a toolkit
of useful widgets), then that requirement would be unreasonable.
Applications will define their own classes for tree structures. They
shouldn't be forced to use our Tree abstract class. Different tree
structures will have different interfaces.
Pluggable adapters. Let's look at three ways to implement pluggable adapters
for the TreeDisplay widget described earlier, which can lay out and display
a hierarchical structure automatically.
The first step, which is common to all three of the implementations discussed
here, is to find a "narrow" interface for Adaptee, that is, the smallest
subset of operations that lets us do the adaptation. A narrow interface
consisting of only a couple of operations is easier to adapt than an
interface with dozens of operations. For TreeDisplay, the adaptee is any
hierarchical structure. A minimalist interface might include two
operations, one that defines how to present a node in the hierarchical
structure graphically, and another that retrieves the node's children.
Then there are two use cases
"Narrow Interface" being made as abstract and part of the TreeDisplay
Class
Narrow Interface extracted out as a separate interface and having a composition of it in the TreeDisplay class
(There is a 3rd approach of Parameterized adapter also but skipping it for simplicity, Also this 3rd one is I guess more specific to Small talk)
When we talk about the Adapter design pattern, we typically consider two preexisting APIs that we would like to integrate, but which don't match up because they were implemented at different times with different domains. An Adapter may need to do a lot of mapping from one API to the other, because neither API was designed with this sort of extensibility in mind.
But what if the Target API had been designed with future adaptations in mind? A Target API can simplify the job of future Adapters by minimizing assumptions and providing the narrowest possible interface for Adapters to implement. Note this design requires a priori planning. Unlike typical use cases for the Adapter pattern, you cannot insert a Pluggable Adapter between any two APIs. The Target API must have been designed to support pluggable adaptations.
Q1) This is what the GoF means by built-in interface adaptation: an interface is built into the Target API in order to support future adaptations.
Q2) As mentioned, this is a relatively unusual scenario for an Adapter, since the typical strength of the pattern is its ability to handle APIs that have no common design.
The GoF lists three different approaches to design a Target API for adaptation. The first two are recognizable as a couple of their Behavioral design patterns.
Template Method
Strategy
Closures (what Smalltalk calls code blocks)
Q3) Without getting caught up in details of the GoF's GUI examples, the basic idea behind designing what they call a "narrow interface" is to remove as much domain specificity as possible. In Java, the starting point for a domain-agnostic API would almost certainly be the functional interfaces.
A Target API with dependencies on these interfaces should be much simpler to adapt than an API built around domain-specific methods. The former allows for creation of Pluggable Adapters, while the latter would require a more typical Adapter with heavy mapping between APIs.
Let me share a couple of thoughts.
First, since the question has been posted with the Smalltalk tag, I'll use the Smalltalk syntax which is less verbose (e.g. #children instead of GetChildren(Tree,Node), etc.)
As an introduction to this issue (which may be useful for some readers), let's say that (generic) frameworks need to use a generic language (e.g. #children). However, generic terms may not be natural for the specific object you are considering. For example, in the case of a File System, one usually has #files, #directories, etc., but may not have the selector #children. Even if adding these selectors won't kill anyone, you don't want to populate your classes with new "generic" selectors every time an "abstract" class imposes its naming conventions. In the real life, if you do that, sooner or later you will end-up having collisions with other frameworks for which the very same selector has a different meaning. This implies that every framework has the potential of producing some impedance (a.k.a. friction) with the objects that try to benefit from it. Well, adapters are meant to mitigate these side effects.
There are several ways to do this. One is making your framework pluggable. This means that you will not require the clients to implement specific behavior. Instead you will ask the clients to provide a selector or a block whose evaluation will produce the required behavior.
In the Directory example, if your class Directory happens to implement, say #entities, then instead of creating #children as a synonym, you will tell the appropriate class in the framework something like childrenSelector: #entities. The object receiving this method will then "plug" (remember) that it has to send you #entities when looking for children. If you don't have such a method, you still can provide the required behavior using a block that does what's needed. In our example the block would look like
childrenSelector: [self directories, self files].
(Side note: the pluggable framwork could provide a synonym #childrenBlock: so to make its interface more friendly. Alternatively, it could provide a more general selector such as childrenGetter:, etc.)
The receiver will now keep the block in its childrenGetter ivar and will evaluate it every time it needs the client's children.
Another solution one might want to consider consists in requiring the client to subclass an abstract class. This has the advantage of exposing very clearly the client's behavior. Note however than this solution has some drawbacks because, in Smalltalk, you can only inherit from one parent. So, imposing the superclass may result in an undesirable (or even unfeasible) constraint.
The other option you mention consists in adding one indirection to the previous one: instead of subclassing the main "object" you offer an abstract superclass for subclassing the behavoir your object needs to adapt. This is similar to the first approach in that you don't need to change the client, except that this time you put the adapted protocol in a class by itself. This way, instead of plugging several parameters into the framework, you put them all in an object and pass (or "plug") that object to the framework. Note that these adapting objects act as wrappers in that they know the real thing, and know how to deal with it for translating the few messages the framework needs to send. In general, the use of wrappers provides a lot of flexibility at the cost of populating your system with more classes (which entails the risk of duplicated hierarchies). Moreover, wrapping many objects might impact the performance of your system. Note by the way that GraphicNode also looks like a wrapper of the intrinsic/actual Node.
I'm not sure I've answered your question, but since you asked me to somehow expand my comment, I've happily tried so.
Q1) Interface adaptation just means adapting one interface to implement another, i.e., what adapters are for. I'm not sure what they mean by "built-in", but it sounds like a specific feature of Smalltalk, with which I'm not familiar.
Q2) A "Pluggable Adapter" is an adapter class that implements the target interface by accepting implementations for its individual methods as constructor arguments. The purpose is to allow adapters to be expressed succinctly. In all cases, this requires the target interface to be small, and it usually requires some kind of language facility for succinctly providing a computation - a lambda or delegate or similar. In Java, the facility for inline classes and functional interfaces means that a specific adapter class that accepts lambda arguments is unnecessary.
Pluggable adapters are a convenience. They are not important beyond that. However...
Q3) The quoted text isn't about pluggable adapters, and neither of the two use cases has a pluggable adapter in it. That part is about the Interface Segregation Principle, and it is important.
In the first example, TreeDisplay is subclassed. The actual adapter interface is the subset of methods in TreeDisplay that require implementation. This is less than ideal, because there is no concise definition of the interface that the adapter must implement, and the DirectoryTreeDisplay cannot simultaneously implement another similar target interface. Also such implementations tend interact with the subclass in complex ways.
In the second example, TreeDisplay comes with a TreeAccessorDelegate interface that captures the requirements for things it can display. This is a small interface that that can be easily implemented in a variety of ways, including by a pluggable adapter. (although the example DirectoryBrowser is not pluggable). Also, interface adaptation does not have to be the sole purpose of the adapter class. You see that DirectoryBrowser class implements methods that have nothing to do with tree display.
The Node type in these examples would be an empty/small interface, i.e., another adapter target, or even a generic type argument so that no adaptation is required. I think this design could be improved, actually, by making Node the only adaptation target.

Should I pass information inside Observer Events

I have an Event Login. I plan to populate that event with information such as this:
// Class A.
Login login = new Login();
login.setUsername(userName);
observer.notifyEvent(login);
The idea is for class B to get this information.
Is this bad practice? If so why?
The only forseable problem is that some other part of the software will be listening to this for no reason. When in reality only one class should be getting the information.
The only advantage is that all my classes are connected to the Observer object, but not connected to each other. In other words, if I wanted to pass the username I would need to connect A and B. Which I would only do in extreme circumstances.
Not much of a problem. - However, you may want to include the "sender" of the event in the event object so that the listener can identify where it comes from and, if needed, can get further state information from the event source.
The Observer pattern allows you to decouple the source of the event from the consumers of an event.
This is generally a good idea, even if you are only going to register one consumer.
However, I'll recommend you not to use the java.util.Observer which uses plain java.lang.Object as events, which means you must check the event object via instanceof and cast to the appropriate class.
I think its better to use an Observer or Listener implementation which supports generic types, such as Spring's ApplicationListener or Guava's EventBus which allow you to register Listener for events of particular class type, such as Login.class in your example.
Well, you probably need to dive a bit deeper into the original GoF book. For such a situation when a developer cares about different components that might be interested in different types of events the book offers the subjects collection that is maintained by the ChangeManager.
So when a component is interested in a specific type of event it passes a specific subject to the Register method so that this component won’t receive the updates for the events that represent a different subject. Additional advantage is the further decreasing of coupling.
Alternatively you might end up with building the system where any component that is plugged to the wire listens to all the events but that solution is too generic and adds lots of risks to the implementation (e.g. in the runtimes with automatic memory management like .NET the garbage collector won’t collect the subscriber while it is listening to any event – just because the ChangeManager still maintains a reference to it). It adds an additional responsibility to the subscriber - it has to do the additional filtering of events analyzing their type.
The rule of thumb is that you don’t need to subscribe for a specific event if you’re not interested to be notified when it occurs.
Referring to your example it is much better to introduce the Login subject and not to subscribe to it any component that is not interested in this specific subject.

How can I apply oo design patterns in this situation?

Situation: Suppose we're designing the UI of Windows 9 using Java API. We need to build up 3 classes main, BuildInWindow and ApplicationWindow.
main - the window for rendering the system UI (i.e. the start botton & wallpaper page)
BuildInWindow- windows for rendering buildt-in apps (e.g. IE)
ApplicationWindow- windows for rendering apps from third party (e.g. eclipse)
all of them have to implement 3 Java API interfaces, WindowFocusListener, WindowListener and WindowStateListener and have the methods onExit() and onCrushing().
onExit() performs when the system/built-in app/ third-party app is shut down normally
onCrushing() captures any system/application crush and send system state back to server
This is the original design:
http://i.stack.imgur.com/JAJiY.png
I have some ideas of how to design it in a OO manner, but I am not sure if that's the right way. Here's my thoughts:
Create an abstract class with method onExit() and onCrushing(). Since the code of onExit()would vary from 3 classes, it should be an abstract method & onCrushing()would be same fo all classes, so it would be an concrete method
tHE MAIN WINdow should use singleton design to ensure user only create one instance of main.
Use the facade design to save the trouble of implementing 3 interfaces to three classes
My question is I don't really understand facade design, so I am not sure if it can be applied in this case. Also I am not really sure if onExit() would be different for 3 classes and onCrushing() would perform the same function.
I tried my best to explain the question clearly...if you don't understand free free to comment. Thank you very much!
I've left some questions in a comment linked to your question but here's some guidance for you:
You shouldn't create an abstract class on the basis of both BuildInwindow and ApplicationWindow both having to have methods #onExit and #onCrushing if they are not to share any implementation. Abstract classes are most useful where there is a common implementation. An interface containing these methods would be sufficient. That said, your two windows may share other functionality and, if so, it could be shared through a common superclass (abstract if it relies on subclass implementation detail). You may find the Template Method pattern useful for managing the overall window mechanism with specific tailoring for different window types. You may also find the Factory Method means of instance creation (for your window classes) will help separate the object creation and set-up from the creation mechanism.
A single shared instance would seem sensible and a singleton would serve this purpose (so long as you're able to handle termination, etc). Alternatively, your application may just launch a single Main instance - you may even just hide the constructor through package access to ensure no others are created.
The facade pattern just serves to simplify a complex interface. It mainly does this by rolling calls to collaborating instances together under a single (coarser) interface. This wouldn't normally be a done to hide which interfaces a class supports. Indeed, publishing which interfaces a class extends is important to API users. You could roll the three interfaces into a single interface for "convenience" but I think this is unnecessary. If you do settle on a common superclass then that would "extend" the three interfaces (if all subclasses were expected to support them). It may also implement some default implementation of these interfaces (again, watch access modifiers to ensure those you intend to be can be overridden while others may be final).
Edit: Guidance
You just have to identify the classes and relationships:
I suggest you just grab some paper and draw. You already have your nouns and verbs (you can otherwise go noun and verb spotting to identify classes and methods on them).
So, why not draw a simple diagram containing all the info (A, B, C, Main, etc) and draw the relationships between them. This is your start point. You may have some confusion when working out how Main links to the window classes (given there are two kinds). Just write a note on it and move on to clarify the rest of the picture.
Next, refine your diagram to start moving common features into a single place (abstraction). You know this exists with regards to your interfaces and the methods you suggest but you may need to decide which (if any) have any common functionality. Then decide if interfaces satisfies your needs (methods are common but implementations are different) or if the implementation itself is the same and so a parent superclass may be useful (this addresses abstraction [who is responsible for what], encapsulation [individual implementations at the appropriate level] and polymorphism [which classes support common methods]). Note that, even if you settle on an superclass, you'd be wise to back it with an interface (it makes introduction of sibling or replacement classes easier in time - think maintenance).
Next, work on the issues you found. Has your draft design clarified any of them? For instance, your Main needs to know about its windows but - what type are they? So, has any of your refinement made this clearer?
Do any patterns present themselves? for this you need to already have a feel for design patterns I'm afraid so buy and absorb the GoF Design Patterns book. It'll put you in good stead for spotting patterns as you go. I'd also recommend reading this specific book before taking on any others as it's technology agnostic (and some other books arebloated with tech-specific workarounds). Perhaps study the two patterns I pointed out and see if they fit your requirement.
On the whole though, your ideas seem to be going in the right direction.

Why do we need interfaces to achieve event listeners in java?

I have this doubt in Java: when people are writing an event listener they implement an interface and they define a particular function in the interface to achieve a particular task. My doubt is instead of implementing an interface can we just define the function with the an appropriate name.
Also, how interfaces help in achieving event listeners?
Because many different classes would want to listen to the same event and Java does not allow multiple inheritance.
The Listener interface gives you a lot a implementation freedom.
This way you don't have to implement a specific function in a specific class. Though implementing an interface seemes to be the same, it isn't. The functionality of a listener is just still ja single function, but the function is usualy in a lightweight object. Yet you are able to implement a lot of program mechanics inside a listener, if you need to.
Also, you can change the listeners at runtime. You can't change an overriden function.
There are a lot of good reasons to use composition (over inheritance) here.
If you really want to understand this, I encourage you to look inside "Heads first: Design Patterns". The "look inside" feature of amazon contains the complete chapter 1, which explains this pattern greatly.

Why property change listener instead of observable

I was having problems with class design until i found out about observable (using observer design pattern) and thus created a small application using it which solved my problem. I was happy and proud that I had used a good principle to sovle a problem.
Now i am about to start my main application and have just read this
Making a JFrame and Observable Object
Why is the poster advised against the use of observable and instead told to use propertychangelistenr? Is there any issues with using observable?
Regards
Observer and Listener pattern are very similar. But Observer has a weakness: all observables are the same. You have to implement the logic that is based on instanceof and cast object to concrete type into Observable.update() method.
Listeners are different. There are a lot of listener types. For example mouse listener, keyboard listener etc. Each one has several callback methods (i.e. keyPressed(), keyReleased() etc). So, you never have to implement the logic that should answer the question "is it my event" into the event handler.
I think that this is why listener model is preferable.
DejanLekic and others have probably by now realized, that Observable is not an interface. That is the whole problem with Java.util.Observable!
The user of Observable has to inherit from it, and nothing else.
Consider Java.RMI or Listener events.
The only right answer is "it depends".
Observable is good when you don't care what changes about an object; you only want to know that something changed and update e.g. a cache of object properties. It's interface is just too coarse, but it could be a time-saver if you just have a need for such a thing.
On the other hand, as AlexR noticed, you also don't know what type of argument gets passed in before hand (it can even be a null value!). This makes it harder to do something useful with it. A proper listener class can have a richer API, but at the cost of adding a Listener interface and event class to your project.
PropertyChangeListener is a special case of the Observable pattern. That is I guess that both solution is good from a design perspective. Meanwhile as far as I remember PropertyChangeListener has some built in support hence it might require less coding. Ie. see: http://download.oracle.com/javase/1.4.2/docs/api/java/beans/PropertyChangeSupport.html.
The difference is in how you use them. Most of the time subclasses of Observable have no particular implementation - you inherit from it just to get a new type of Observable. Listeners on the other hand implement particular interface (or top level EventListener interface) and therefore MUST implement certain methods.

Categories