Intro to Java Observer Pattern

We are well into this whole patterns thing now, picking up lots of new lingo, and becoming better at communicating with other developers. Next on the list: the observer pattern. This is an important pattern to use to help prevent tight coupling and keep code separated into discrete objects. This pattern allows communication between two objects at particular times without each object needing to be too tightly coupled to the other.

The Observer in the Physical World

The idea behind the observer is like a subscription. Do you have a newspaper or magazine subscription? Have you signed up for cell phone texts from your favorite band when they have new tour dates? The act of you signing up with the newspaper, the magazine, or the band, is you saying you want a subscription, or that you want to become an observer. When the subject (newspaper, magazine, band) has something new to share (on a schedule or not) they run down their subscriber list, and notify the observers by mail, or text.

The Observer in the Software World

On the software side, the idea is the same. Your subject needs to provide a way to take subscriptions, hold a list of observers, and when a particular state changes, notify them. There is usually a couple of methods on the subject that takes in an interface that is used for getting on or off the subscription list. On this interface is also the “call back” method. This is the method that the subject will execute when it wants to inform the observers of state changes.
Continue reading

Intro to Java Decorator Pattern

This entry is part 13 of 13 in the series Intro to Java

We have looked at the Factory, the Adapter, and the Singleton patterns. Now we look at the Decorator. The Decorator is similar to the Adapter, but with a subtle difference. With our ReptileAdapter, we wrapped the Reptile class to map the interface methods of Animal to the appropriate methods on Reptile. With the Decorator we also wrap a class, but to add functionality, not to map it or replace the functionality.

The Decorator in the Physical World

The idea behind decorating things in the real world is pretty much how it sounds. We wrap an object with new functionality, while keeping the old functionality. How about a camera in a waterproof housing? When closed up, we have added the functionality of waterproofing, but we still provide a way to press the buttons and turn the dials so that the camera can be operated.

The Decorator in the Software World

On the software side, the idea is the same. It is usually used when we have one object that we like how it functions, but we want to augment the behavior for a different situation. Done correctly, we can keep inserting one object inside another adding functionality at every step.
Continue reading