|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.
As ridesharing competitors and enhanced services increase, notable changes are occurring in the transportation model. Despite the cost-effective means and flexibility of ridesharing, both drivers and users will need to be aware of the connected environment and how it will impact the ridesharing experience. In his session at @ThingsExpo, Timothy Evavold, Executive Director Automotive at Covisint, will discuss key challenges and solutions to powering a ride sharing and/or multimodal model in the a...
Oct. 23, 2016 03:30 PM EDT Reads: 1,467
SYS-CON Events announced today that Coalfire 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. Coalfire is the trusted leader in cybersecurity risk management and compliance services. Coalfire integrates advisory and technical assessments and recommendations to the corporate directors, executives, boards, and IT organizations for global brands and organizations in the technology, cloud, health...
Oct. 23, 2016 03:30 PM EDT Reads: 1,511
A completely new computing platform is on the horizon. They’re called Microservers by some, ARM Servers by others, and sometimes even ARM-based Servers. No matter what you call them, Microservers will have a huge impact on the data center and on server computing in general. Although few people are familiar with Microservers today, their impact will be felt very soon. This is a new category of computing platform that is available today and is predicted to have triple-digit growth rates for some ...
Oct. 23, 2016 03:00 PM EDT Reads: 34,022
SYS-CON Events announced today that Transparent Cloud Computing (T-Cloud) Consortium 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. The Transparent Cloud Computing Consortium (T-Cloud Consortium) will conduct research activities into changes in the computing model as a result of collaboration between "device" and "cloud" and the creation of new value and markets through organic data proces...
Oct. 23, 2016 02:15 PM EDT Reads: 1,309
Cognitive Computing is becoming the foundation for a new generation of solutions that have the potential to transform business. Unlike traditional approaches to building solutions, a cognitive computing approach allows the data to help determine the way applications are designed. This contrasts with conventional software development that begins with defining logic based on the current way a business operates. In her session at 18th Cloud Expo, Judith S. Hurwitz, President and CEO of Hurwitz & ...
Oct. 23, 2016 02:00 PM EDT Reads: 4,439
Major trends and emerging technologies – from virtual reality and IoT, to Big Data and algorithms – are helping organizations innovate in the digital era. However, to create real business value, IT must think beyond the ‘what’ of digital transformation to the ‘how’ to harness emerging trends, innovation and disruption. Architecture is the key that underpins and ties all these efforts together. In the digital age, it’s important to invest in architecture, extend the enterprise footprint to the cl...
Oct. 23, 2016 01:00 PM EDT Reads: 1,780
SYS-CON Events announced today that MathFreeOn 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. MathFreeOn is Software as a Service (SaaS) used in Engineering and Math education. Write scripts and solve math problems online. MathFreeOn provides online courses for beginners or amateurs who have difficulties in writing scripts. In accordance with various mathematical topics, there are more tha...
Oct. 23, 2016 12:45 PM EDT Reads: 970
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
Oct. 23, 2016 12:30 PM EDT Reads: 4,513
@ThingsExpo has been named the Top 5 Most Influential Internet of Things Brand by Onalytica in the ‘The Internet of Things Landscape 2015: Top 100 Individuals and Brands.' Onalytica analyzed Twitter conversations around the #IoT debate to uncover the most influential brands and individuals driving the conversation. Onalytica captured data from 56,224 users. The PageRank based methodology they use to extract influencers on a particular topic (tweets mentioning #InternetofThings or #IoT in this ...
Oct. 23, 2016 12:00 PM EDT Reads: 8,352
@ThingsExpo has been named the Top 5 Most Influential M2M Brand by Onalytica in the ‘Machine to Machine: Top 100 Influencers and Brands.' Onalytica analyzed the online debate on M2M by looking at over 85,000 tweets to provide the most influential individuals and brands that drive the discussion. According to Onalytica the "analysis showed a very engaged community with a lot of interactive tweets. The M2M discussion seems to be more fragmented and driven by some of the major brands present in the...
Oct. 23, 2016 11:30 AM EDT Reads: 11,327
In the next forty months – just over three years – businesses will undergo extraordinary changes. The exponential growth of digitization and machine learning will see a step function change in how businesses create value, satisfy customers, and outperform their competition. In the next forty months companies will take the actions that will see them get to the next level of the game called Capitalism. Or they won’t – game over. The winners of today and tomorrow think differently, follow different...
Oct. 23, 2016 11:00 AM EDT Reads: 941
In an era of historic innovation fueled by unprecedented access to data and technology, the low cost and risk of entering new markets has leveled the playing field for business. Today, any ambitious innovator can easily introduce a new application or product that can reinvent business models and transform the client experience. In their Day 2 Keynote at 19th Cloud Expo, Mercer Rowe, IBM Vice President of Strategic Alliances, and Raejeanne Skillern, Intel Vice President of Data Center Group and ...
Oct. 23, 2016 10:30 AM EDT Reads: 1,464
The Internet of Things (IoT), in all its myriad manifestations, has great potential. Much of that potential comes from the evolving data management and analytic (DMA) technologies and processes that allow us to gain insight from all of the IoT data that can be generated and gathered. This potential may never be met as those data sets are tied to specific industry verticals and single markets, with no clear way to use IoT data and sensor analytics to fulfill the hype being given the IoT today.
Oct. 23, 2016 09:45 AM EDT Reads: 2,510
More and more brands have jumped on the IoT bandwagon. We have an excess of wearables – activity trackers, smartwatches, smart glasses and sneakers, and more that track seemingly endless datapoints. However, most consumers have no idea what “IoT” means. Creating more wearables that track data shouldn't be the aim of brands; delivering meaningful, tangible relevance to their users should be. We're in a period in which the IoT pendulum is still swinging. Initially, it swung toward "smart for smar...
Oct. 23, 2016 09:45 AM EDT Reads: 800
Virgil consists of an open-source encryption library, which implements Cryptographic Message Syntax (CMS) and Elliptic Curve Integrated Encryption Scheme (ECIES) (including RSA schema), a Key Management API, and a cloud-based Key Management Service (Virgil Keys). The Virgil Keys Service consists of a public key service and a private key escrow service.
Oct. 23, 2016 09:45 AM EDT Reads: 1,030
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, will discuss the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Oct. 23, 2016 09:30 AM EDT Reads: 3,828
What happens when the different parts of a vehicle become smarter than the vehicle itself? As we move toward the era of smart everything, hundreds of entities in a vehicle that communicate with each other, the vehicle and external systems create a need for identity orchestration so that all entities work as a conglomerate. Much like an orchestra without a conductor, without the ability to secure, control, and connect the link between a vehicle’s head unit, devices, and systems and to manage the ...
Oct. 23, 2016 08:30 AM EDT Reads: 1,344
Machine Learning helps make complex systems more efficient. By applying advanced Machine Learning techniques such as Cognitive Fingerprinting, wind project operators can utilize these tools to learn from collected data, detect regular patterns, and optimize their own operations. In his session at 18th Cloud Expo, Stuart Gillen, Director of Business Development at SparkCognition, discussed how research has demonstrated the value of Machine Learning in delivering next generation analytics to impr...
Oct. 23, 2016 08:00 AM EDT Reads: 5,691
For basic one-to-one voice or video calling solutions, WebRTC has proven to be a very powerful technology. Although WebRTC’s core functionality is to provide secure, real-time p2p media streaming, leveraging native platform features and server-side components brings up new communication capabilities for web and native mobile applications, allowing for advanced multi-user use cases such as video broadcasting, conferencing, and media recording.
Oct. 23, 2016 07:00 AM EDT Reads: 4,112
Amazon has gradually rolled out parts of its IoT offerings, but these are just the tip of the iceberg. In addition to optimizing their backend AWS offerings, Amazon is laying the ground work to be a major force in IoT - especially in the connected home and office. In his session at @ThingsExpo, Chris Kocher, founder and managing director of Grey Heron, explained how Amazon is extending its reach to become a major force in IoT by building on its dominant cloud IoT platform, its Dash Button strat...
Oct. 23, 2016 06:30 AM EDT Reads: 4,759