|By Steven Schwell||
|October 1, 1997 12:00 AM EDT||
The Observer Design Pattern is among the most useful for object-oriented software design. The JDK itself makes heavy use of a variant of this pattern in the 1.1 AWT event delegation model. The JDK also provides a reusable embodiment of the pattern in the form of the java.util.Observer interface and the java.util.Observable class. If you've done much serious Java programming you've more than likely had occasion to use these classes.
The idea of the pattern is to model a one-to-many dependency without tightly coupling the observed object with its many observers. When the observed object changes in some interesting way it can automatically notify all of its observers without knowing them directly. For more on this pattern, see Qusay Mahmoud's article, "Implementing Design Patterns in Java" (JDJ, Vol. 2, Iss. 5), or the Design Patterns book.
Unfortunately, a number of weaknesses have been identified in the JDK's Observer/Observable classes. Peter Coad and Mark Mayfield discuss some of these weaknesses in their excellent book, Java Design. These weaknesses significantly limit the reusability and power of the classes, which is a shame since powerful reusability is a big part of what object-oriented design is all about.
Most of the weaknesses are due to the fact that java.util.Observable is a class rather than an interface; or rather, that it is a class without a corresponding interface. This implies that the only way to reuse Observable is to subclass it. You can't take an existing class and tack on the role of Observable by having it implement an Observable interface because there is no Observable interface.
What if you have a class that is already in a class hierarchy and also needs to play the role of an Observable? Since Java doesn't support multiple inheritance, you're out of luck. That class cannot extend from Observable because it is already extending from some other class.
It also means that you are stuck with the one and only implementation of Observable in java.util.Observable. For a variety of reasons, you may want to use an alternate implementation - e.g., to do the notification in a separate thread or in a particular order. You may even want to vary the implementation of Observable at runtime. There is no Observable interface for your alternate implementations to implement. You cannot reuse Observable by composition so you cannot vary the composed Observable implementation at runtime.
The designers of the Observable class broke two general principles of object-oriented design with Java. The first principle is to design with interfaces rather than classes. Whenever possible, avoid committing yourself to a particular implementation of an interface. The second principle is to favor reuse by composition over reuse by inheritance unless a class hierarchy is clearly indicated. By omitting an Observable interface and making some of its methods protected, the designers made it impossible to reuse Observable by composition.
A minor weakness in Observable is the necessity to call setChanged() before notifySubscribers(). The intention there seems to be to eliminate needless notifications in cases where there is no interesting change to the Observable. There may be situations in which this two-stage notification is appropriate, but it isn't the simplest case and programmers shouldn't be forced to use this implementation in all situations. Also, setChanged() is protected, further reinforcing the necessity to reuse the class only by inheritance.
Now let's look at the Observer interface. The weakness here is its tight coupling with the Observable class. The first parameter to the update() method is unnecessarily typed as an Observable. If it were typed more generally as a simple Object, the Observer interface would be more reusable. It then could be used with any Observable implementation or even in any situation, completely unrelated to Observer/Observable, which called for a void method with two Object parameters.
Despite all these weaknesses, I was initially reluctant to ignore the JDK classes in favor of the homegrown replacements suggested by Coad and Mayfield. After all, the JDK classes are already locally available to every VM and they do serve their purpose nicely for the majority of cases. On the other hand, designing for maximal reuse is crucial to the success of any object-oriented design. A little forethought early in the game can lead to great savings down the road. Luckily, when I started a new project some months ago, I decided to take the plunge and start using the improved classes.
More recently I began designing a number of distributed three-tier Java apps using Remote Method Invocation (RMI). It turns out that the Observer pattern has great application to remote applications. A remote object that lives on the server often needs to be observed by multiple objects living on multiple clients. When the remote object changes, all clients need to find out in order to, for example, update the user's view.
The JDK's Observer/Observable classes are of no use here. They do not extend from java.rmi.Remote and their method signatures do not allow for the possible throwing of RemoteException. Both of these are required of any Remote interface for RMI. So the JDK's Observable/Observer classes can never be implemented as an RMI remote interface of a RemoteObject.
The solution that I've seen in articles and books is to write a separate set of classes for Remote Observable/Observer. This always seemed wrong to me. Why should I have to write, support and use two disjoint sets of classes to do basically the same thing albeit in different situations? What if I have a class that needs to notify both local and remote Observers? You mean it has to implement both versions of Observable?!
Having already severed my dependence on the JDK's Observable classes, I was able to painlessly enhance my classes to support Remote Method Invocation. The same classes can now be used for local Observers as well as remote Observers or even for a mixture of remote and local Observers.
The interfaces are shown in Listing 1. In order to avoid confusion with the JDK classes, I use the synonymous terminology of Publisher/Subscriber rather than Observable/Observer.
Notice that the Publisher and Subscriber interfaces extend from java.rmi.Remote and all their methods may throw RemoteException. This is so that these interfaces may be implemented by remote classes for use with RMI. These additions do not preclude these classes from being used in a strictly local situation without RMI. In fact, the same Publisher could be used to publish to a mixture of local and remote Subscribers.
A simple basic implementation of Publisher is presented in Listing 2. This Publisher can be used for both local and remote Subscribers.
The notifySubscribers() method deserves some elaboration. The call to the Subscribers' update() method is in a try/catch clause to deal with possibly thrown RemoteExceptions. Two particular RemoteExceptions, ConnectException and NoSuchObjectException, are considered serious enough to consider the Subscriber to be dead. Subscribers that are considered dead are removed from the list of Subscribers for this Publisher. Other RemoteExceptions may be indications of transient failures that could correct themselves. This is the type of fuzzy logic you need to apply in networked situations where errors are unpredictable and non-deterministic.
The dead Subscribers are not removed from the list of Subscribers until after the list is enumerated. At first glance you might ask, why not remove the dead Observers right away, within the catch clauses? This is because of a quirk in java.util.Vector that makes it unsafe to manipulate a Vector while it is being enumerated. This quirk (bug?) is a discussion for another time, but a few words about the workaround I chose are warranted here.
As I discover Subscribers that are to be considered dead, I accumulate them in a Vector. Only after enumeration of all Subscribers do I go through the Vector of dead Subscribers and actually remove them. Another workaround that I could have used is to clone the Vector of Subscribers before enumerating it. Then I could operate on the original Vector while enumerating the clone. I chose the workaround I did because it has little overhead for the more usual case when no RemoteException is thrown. Even the deadSubs Vector is not allocated until and unless it is needed. This technique is known as lazy instantiation.
The preferred way to reuse BasicPublisher is by composition. Any class that needs to play the role of a Publisher should implement the Publisher interface and include a reference to an instance of BasicPublisher to do the work of a Publisher. Listing 3 is a rough outline of this.
Class XX is free to extend from some other class if it needs to and it can publish changes to subscribers, whether local or remote, by calling pub.notifySubscribers(). You can also reuse BasicPublisher by subclassing it, but this is not the preferred way. It eliminates the need to delegate the Publisher interface but it reduces the extendibility of the class because the class can no longer be a subclass of any other class.
To use these classes with RMI, the classes that implement Publisher and Subscriber must be remote objects. Without going into too much detail on RMI, let me just point out that any class can be made remote in two simple steps. First, add the following to its constructor:
UnicastRemoteObject.exportObject(this); and recompile. Second, run the rmic post compiler on the class. That's it. Your class is now remote. Remote publishers can now publish changes to local subscribers in the same VM or to remote subscribers in other VMs.
In summary, these two interfaces and class constitute a far more powerful and reusable embodiment of the Observer design pattern than the JDK's Observer/Observable. They can even be used for remote Observers with RMI. This is just the sort of weapon in your object-oriented arsenal that makes Java programming such a joy.
Gamma, E., Johnson, R. and Vlissides, J., "Design Patterns: Elements of Object-Oriented Architecture", Addison-Wesley, Reading, MA, 1995.
Coad , P. and Mayfield, M., "Java Design: Building Better Apps and Applets", Yourdon Press, Upper Saddle River, NJ, 1997.
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend @CloudExpo | @ThingsExpo, June 6-8, 2017, at the Javits Center in New York City, NY and October 31 - November 2, 2017, Santa Clara Convention Center, CA. Learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
Feb. 19, 2017 11:15 AM EST Reads: 1,572
Have you ever noticed how some IT people seem to lead successful, rewarding, and satisfying lives and careers, while others struggle? IT author and speaker Don Crawley uncovered the five principles that successful IT people use to build satisfying lives and careers and he shares them in this fast-paced, thought-provoking webinar. You'll learn the importance of striking a balance with technical skills and people skills, challenge your pre-existing ideas about IT customer service, and gain new in...
Feb. 19, 2017 11:15 AM EST Reads: 1,632
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 20th International Cloud Expo, which will take place on June 6–8, 2017, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buyers...
Feb. 19, 2017 11:00 AM EST Reads: 1,529
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, Cloud Expo and @ThingsExpo are two of the most important technology events of the year. Since its launch over eight years ago, Cloud Expo and @ThingsExpo have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, I provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading the...
Feb. 19, 2017 10:45 AM EST Reads: 7,621
While not quite mainstream yet, WebRTC is starting to gain ground with Carriers, Enterprises and Independent Software Vendors (ISV’s) alike. WebRTC makes it easy for developers to add audio and video communications into their applications by using Web browsers as their platform. But like any market, every customer engagement has unique requirements, as well as constraints. And of course, one size does not fit all. In her session at WebRTC Summit, Dr. Natasha Tamaskar, Vice President, Head of C...
Feb. 19, 2017 10:30 AM EST Reads: 6,511
In the enterprise today, connected IoT devices are everywhere – both inside and outside corporate environments. The need to identify, manage, control and secure a quickly growing web of connections and outside devices is making the already challenging task of security even more important, and onerous. In his session at @ThingsExpo, Rich Boyer, CISO and Chief Architect for Security at NTT i3, will discuss new ways of thinking and the approaches needed to address the emerging challenges of securit...
Feb. 19, 2017 09:45 AM EST Reads: 1,141
TechTarget storage websites are the best online information resource for news, tips and expert advice for the storage, backup and disaster recovery markets. By creating abundant, high-quality editorial content across more than 140 highly targeted technology-specific websites, TechTarget attracts and nurtures communities of technology buyers researching their companies' information technology needs. By understanding these buyers' content consumption behaviors, TechTarget creates the purchase inte...
Feb. 19, 2017 09:45 AM EST Reads: 730
As cloud adoption continues to transform business, today's global enterprises are challenged with managing a growing amount of information living outside of the data center. The rapid adoption of IoT and increasingly mobile workforce are exacerbating the problem. Ensuring secure data sharing and efficient backup poses capacity and bandwidth considerations as well as policy and regulatory compliance issues.
Feb. 19, 2017 09:15 AM EST Reads: 1,563
Almost two-thirds of companies either have or soon will have IoT as the backbone of their business. Though, IoT is far more complex than most firms expected with a majority of IoT projects having failed. How can you not get trapped in the pitfalls? In his session at @ThingsExpo, Tony Shan, Chief IoTologist at Wipro, will introduce a holistic method of IoTification, which is the process of IoTifying the existing technology portfolios and business models to adopt and leverage IoT. He will delve in...
Feb. 19, 2017 09:15 AM EST Reads: 1,015
SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of SYS-CON's 20th International Cloud Expo, which will take place on June 6–8, 2017, at the Javits Center in New York City, NY. A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great dea...
Feb. 19, 2017 07:45 AM EST Reads: 1,672
SYS-CON Events announced today that LeaseWeb USA, a cloud Infrastructure-as-a-Service (IaaS) provider, will exhibit at the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. LeaseWeb is one of the world's largest hosting brands. The company helps customers define, develop and deploy IT infrastructure tailored to their exact business needs, by combining various kinds cloud solutions.
Feb. 19, 2017 07:30 AM EST Reads: 1,401
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Feb. 19, 2017 05:45 AM EST Reads: 4,723
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, discussed how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.
Feb. 19, 2017 05:00 AM EST Reads: 4,665
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound e...
Feb. 19, 2017 04:00 AM EST Reads: 10,974
We all know that data growth is exploding and storage budgets are shrinking. Instead of showing you charts on about how much data there is, in his General Session at 17th Cloud Expo, Scott Cleland, Senior Director of Product Marketing at HGST, showed how to capture all of your data in one place. After you have your data under control, you can then analyze it in one place, saving time and resources.
Feb. 19, 2017 03:00 AM EST Reads: 3,818
910Telecom exhibited at the 19th International Cloud Expo, which took place at the Santa Clara Convention Center in Santa Clara, CA, in November 2016. Housed in the classic Denver Gas & Electric Building, 910 15th St., 910Telecom is a carrier-neutral telecom hotel located in the heart of Denver. Adjacent to CenturyLink, AT&T, and Denver Main, 910Telecom offers connectivity to all major carriers, Internet service providers, Internet backbones and exchanges.
Feb. 19, 2017 02:30 AM EST Reads: 1,289
SYS-CON Events announced today that Linux Academy, the foremost online Linux and cloud training platform and community, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Linux Academy was founded on the belief that providing high-quality, in-depth training should be available at an affordable price. Industry leaders in quality training, provided services, and student certification passes, its goal is to c...
Feb. 19, 2017 02:30 AM EST Reads: 759
Web Real-Time Communication APIs have quickly revolutionized what browsers are capable of. In addition to video and audio streams, we can now bi-directionally send arbitrary data over WebRTC's PeerConnection Data Channels. With the advent of Progressive Web Apps and new hardware APIs such as WebBluetooh and WebUSB, we can finally enable users to stitch together the Internet of Things directly from their browsers while communicating privately and securely in a decentralized way.
Feb. 19, 2017 01:15 AM EST Reads: 3,920
The IoT industry is now at a crossroads, between the fast-paced innovation of technologies and the pending mass adoption by global enterprises. The complexity of combining rapidly evolving technologies and the need to establish practices for market acceleration pose a strong challenge to global enterprises as well as IoT vendors. In his session at @ThingsExpo, Clark Smith, senior product manager for Numerex, discussed how Numerex, as an experienced, established IoT provider, has embraced a new m...
Feb. 19, 2017 12:45 AM EST Reads: 2,871
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo 2016 in New York. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place June 6-8, 2017, at the Javits Center in New York City, New York, is co-located with 20th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry p...
Feb. 18, 2017 09:45 PM EST Reads: 653