Friday, September 28, 2012

Decorator Pattern and Java

So, you want to extend behavior but want to avoid subclassing? Then the Decorator Pattern is for you. Decorators change behavior by adding new functionality to the components they decorate without modifying those components. This pattern is based on the Open-Closed OO principle:
Classes should be open for extension but closed for modification.
Designs must be flexible and opened for behavior extension but without modifications to existing code. That way, you avoid introducing new bugs to previous tested and reliable code. Let's check the definition of the Decorator pattern, according to the Head First Design Patterns book:
Attach additional responsabilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
And the basic class diagram for this pattern is as follows:

Let's review each class from the above diagram:
  • Component: Most of the time it's an abstract class with abstract methods. Represents the base class of the hierarchy.
  • ConcreteComponent: Concrete class that implements the methods from the abstract Component class, during the implementation of the methods you should define default behavior.  It's the real class you want to decorate. You may have as many ConcreteComponent classes as you need.
  • Decorator: Base class for decorators, it's abstract so decorators are required to implement the abstract methods. It's composed with a reference to the Component class, so decorators may access the object they are decorating. Notice that both ConcreteComponent and Decorator subclass the Component class, that way decorators may be transparent to you, I mean, you are going to have a reference to a Component object and it may or may not be decorated, you just don't know (or care).
  • ConcreteDecorator: A concrete decorator that implements the methods from the abstract Decorator class. It's the class that executes the real job of decorating. It can access the object it is decorating.  You can have as many ConcreteDecorator classes as you need.

OK, that's kind of confusing, I know. Let's see a real example of the Decorator pattern in action so you can understand the concept. If you have used the API you have already used this pattern, just think about opening streams from a file:

//in a class...
public void printLines(String file) throws Exception
  DataInputStream rin = null;
  rin = new DataInputStream(new FileInputStream(file));

  //more code...

The last piece of code is making use of the Decorator Pattern, it is decorating a so we can read primitive Java data types instead of bytes. Let's review the most important points:

As you can see, every decorator adds behavior to a component (in this case to a FileInputStream so it can read primitive Java data types). The following diagram was generated using Architexa's Free Tool for Understanding Code and it shows the relations between the input-stream classes we were talking about (and some others) and we can see the exact same structure of the Decorator Pattern:

Something to be aware of is that every decorator is another class in your design, so if you have a lot of decorators, your design will have a lot of small classes and it may become complex.

One last thing, remember the most important OO Principle of all: Always use the simplest solution that meets your needs, even if it doesn't include a pattern.

See ya!


Freeman Eric and Freeman Elisabeth and Sierra Kathy and Bates Bert (2004). Head First Design Patterns. United States of America: O'Reilly Media, Inc.

Wednesday, September 26, 2012

Observer Pattern and Java

"Don't call us, we'll call you"... that's the Hollywood OO (Object Oriented) Principle and it's exactly what the Observer pattern is about. In this post we'll review this pattern and how it is used in Java, you may already have used it without knowing...

According to Head First Design Patterns book, this is the definition of the Observer pattern:
Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Sounds familiar? Have you ever worked with Swing? Looks like the event handling mechanism is using the Observer Pattern. Let's think about it, suppose you have a JButton and you want other objects to be notified when the button is pressed... have you done that? sure! The other objects are not asking all the time to the button whether it is pressed or not, they only wait for a notification from the button. Swing does it using the java.awt.event.ActionListener, but in essence it is using the Observer Pattern, even if we are not using  interfaces like java.util.Observer or classes like java.util.Observable...

Now, talking about observers and observables, this two exist since JDK 1.0 and you can use them to implement the Observer Pattern in your applications. Let's see the how to do it:

The objects you want to be waiting for notifications are called Observers, they implement the interface java.util.Observer. This interface defines only one method: +update(Observable,Object):void which is called whenever the observed object is changed. The first parameter, an Observable, is the object that changed. The second parameter may be used as follows:

  • If using PUSH notifications, the Object parameter contains the information needed by the observers about the change. 
  • If using PULL notifications,  the Object parameter  is null and you should use the Observable parameter in order to extract the information needed.

When to PUSH or PULL? It's up to your implementation. The Object you want to be observed is called the Observable and it has to subclass the java.util.Observable class. Yes, subclass. That's the dark side of the built-in implementation of the Observer Pattern in Java, sometimes you simply can't subclass, we'll talk about this in a minute... Once subclassed, you will inherit the following methods, among others:

  • +addObserver(Observer):void which adds the Observer passed in as parameter to the set of observers.
  • +deleteObserver(Observer):void which deletes the Observer passed in as parameter from the set of observers.
  • setChanged():void which marks the Observable as having been changed. This method is protected, so  you can only call it if you subclass the  java.util.Observable class. Call it before notifying your observers.
  • +notifyObservers():void which notifies the registered observers using PULL. It means that when the +update(Observable,Object):void is invoked on the Observer, the Object parameter will be null.
  • +notifyObservers(Object):void  which notifies the registered observers using PUSH. It means that when the +update(Observable,Object):void is invoked on the Observer, the Object parameter will be the same parameter passed in the +notifyObservers(Object):void .

So, what happens if the class you want to be the Observable is already subclassing another class? Well, then you have to write your own Observer Pattern implementation because you can't use the one built-in Java. The following diagram shows you the basic concepts of the Observer Pattern, so you can built your own implementation:

One last thing, remember the most important OO Principle of all: Always use the simplest solution that meets your needs, even if it doesn't include a pattern.

See ya!


Freeman Eric and Freeman Elisabeth and Sierra Kathy and Bates Bert (2004). Head First Design Patterns. United States of America: O'Reilly Media, Inc.

Duke's choice award 2012 is coming to LAD

Duke's Choice Award 2012 LAD
Hello all, I have great news!! The tenth year running Duke's choice award program is expanding and will focus on regional winners from Latin America (LAD), Europe Middle East Africa (EMEA), and Asia. The goal of the regional awards is to celebrate Java innovation happening within specific regions and provides an opportunity to recognize winners locally.

The program looks for the most compelling implementations of Java technology. Innovation is the only criteria. The nomination form can be found on the Duke's Choice site

Winners will be announced on stage during JavaOne LAD (Brasil) December 4th through 6th, and will also be featured in the January/February issue of Java Magazine. Winners will receive a free JavaOne LAD full conference pass and a Duke's Choice Award Statue.

So, you are in Latin America (LAD) and have an innovative Java project? what are you waiting for? The end date for nominations is October 30th, 2012.

Don't you know if you got what it takes? Check the 2011 winners (when there was only one global program).

more info: Duke's Choice site

see ya!

Tuesday, September 25, 2012

Packt Publishing reaches 1000 titles milestone

Extra! Extra!

Hello, I want to share with you all the following press release from Packt Publishing which is celebrating its title number one thousand! And the celebration includes a surprise gift for those who sign up for a free account before 30-Sep-2012 at 

I like packt titles, I already did a review of one of their books: Java 7 New Features Cookbook and I can tell how well they are written and updated. So hurry up, create your free account and wait for your surprise gift! If you already have an account, then you already qualify for the surprise gift.

Press Release
Birmingham-based IT publisher Packt Publishing is about to publish its 1000th title. Packt books are renowned among developers for being uniquely practical and focused.  Packt books cover highly specific tools and technologies which IT professionals might not expect to see a high quality book on.

Packt would like you to join them in celebrating this milestone with a surprise gift – to get involved you just need to have already registered, or sign up for a free Packt account before 30th September 2012.
Packt published their first book in April 2004. One of the most prolific and fastest growing tech book publishers in the world, they now have books on everything from web development to web graphics, e-learning to e-commerce, IT architecture to games, and app development.

Packt supports many of the Open Source projects covered by its books through a project royalty donation, which has contributed over £300,000 to Open Source projects up to now. As part of the celebration Packt is allocating $30,000 to share between projects and authors in a genuinely unique way, soon to be disclosed on their website.

Dave Maclean, founder of Packt Publishing explains, “At Packt we set out 8 years ago to bring practical, up to date and easy to use technical books to the specialist tools and technologies that had been largely overlooked by IT publishers. Today, I am really proud that with our authors and partners we have been able to make useful books available on over 1000 topics and make our contribution to the development community.”

For more information about Packt, the kind of books they publish, and to sign-up for a free account before the 30th of September, 2012, please visit their website:

Java 7 conference at UAO - Summary

Hello again. My participation at UAO's event "Día de la Informática y la Multimedia" was a success, I had my talk about Java 7 on Thursday September 20 and it went pretty well. It was a lot of fun, we had about 50-60 assistants, most of them students and some teachers. Few questions were asked at the end of the presentation, I post some of them here giving further explanation:

Q: What happens if there are exceptions when the try with resources automatically calls the close method?
A: The new Interface java.lang.AutoCloseable defines only one method: close():void which throws a java.lang.Exception. So when you define your resources in a try with resources structure, the compiler will warn you about catching the exception. So, whichever exception is thrown during the execution of the close():void method, you will be able to catch it in your try with resources structure.
Something I didn't mention during the presentation, is that there are new methods in the java.lang.Throwable class that allows you to keep track of all the exceptions that were suppressed in order to deliver a specific exception. The methods are:

Q: What about IPv6 support in Java 7?
A: According to this documentation, Java began supporting IPv6 since J2SE 1.4 back in February 2002, but only Solaris and Linux OS were supported. Since version J2SE 1.5 Windows OS is also supported. Even though, there are some considerations you should be aware of if you want your java IPv4 applications running on IPv6, for example:

Q: Any support for 3D?
A: Java 3D is a special API that enables the creation of three-dimensional graphics applications and Internet-based 3D applets. It is not part of the Java SE so you have to download it and add it to your application libraries. For more information about this API, check its official home page.

Q: What else has Java for developers?
A: The Java platform offers a lot to developers, it allows them to build cross-platform applications. "Write once, run everywhere" is a serious thing to Java. It is everywhere from PCs, to TVs, phones, mobile devices, bluerays,  kindles... etc. The features that every release of Java SE offers are the base of the Java platform.

Java 7, 1+ año después
That was the name of my presentation and you can download it using the following link: Download PDF File
More info about the event can be found here (spanish).

See ya!

Saturday, September 22, 2012

Java 7 conference for ASUOC - Summary

Colombia Oracle Users Group
Hello again. My participation at ASUOC's meeting was a success, I had my talk about Java 7 on Thursday September 13, and it went pretty well. It was a lot of fun, we had about 30 assistants on site and 1027 visitors online (according to the streaming stats). Few questions were asked at the end of the presentation, I post some of them here, giving further explanation:

Q: Is there really any difference in performance when migrating if-else structures to switch structures?
A: There are a lot of discussions about this topic, but if you look at the decompiled code, you will notice that a switch with String cases is translated into two switches at compile time. In the first one, every case is an if statement and if there are Strings with the same hash code, then you'll get an if-else-if statement. So what if many of your String objects have the same hash code?... You will get a long (depending in your cases)  if-else-if statement inside a switch statement and then, the performance of the application may not be the best (but not the worst).
Anyway, I think it is hard to get many String objects with the same hash code in a real scenario, this is a good feature and I'm pleased we have it now.

Q: Do you know if there have been issues with applications compiled for previous versions of Java when running in Java 7?
A: There is a list of Deprecated API that you should be aware of, so you don't use it in your code: Java 7 Deprecated API
On the other hand, some companies publish something called "certification matrix" for their products, so you can know if they can work with some technology, like Java 7. For example, Oracle E-Business Suite is not yet certified to be used with Java 7.

Q: Did you make any change to the NIO.2 example in order to run it in Linux OS?
A: The NIO.2 example was the same for Windows OS as for Linux OS. In Java there's a saying "write once, run everywhere" so you can run the same code in a Windows or Linux machine. Nevertheless, you should know that different file systems have different notions about which attributes should be tracked for a file, as noted in the Managing Metadata (File and File Store Attributes) Tutorial.

Java 7, 1+ año después
That was the name of my presentation and you can download it using this link (in spanish): Download PDF File.

The presentation was also recorded but is not uploaded yet. I will update this post as soon as the presentation is available.
Following you will find the links to the conference (spanish, 01:30 aprox.):

See ya!

Wednesday, September 19, 2012

Java 7 conference at UAO

Hello all, continuing with the Java 7 conference series, I've been invited to talk about Java 7 at Universidad Autónoma during its event: "Día de la Informática y la Multimedia", so if you are around and want to learn the new features that Java 7 has for you, please come and join us. I will be presenting Project Coin, NIO.2 and the Fork/Join Framework. Pretty much the same content as the conference at Universidad Icesi last week.

The information of my presentation is as follows:

WhereUniversidad Autónoma
Aulas 4 Torreon 1A
Cali, Colombia
WhenSeptember 20th 2012
14:00 - 15:30 (GMT-5)

More info (in spanish):
Universidad Autonóma

See ya!

Monday, September 10, 2012

Java 7 conference for ASUOC

Colombia Oracle Users Group
Hello all, I'm attending a Colombia Oracle Users Group meeting this week and I'll be speaking at it about Java 7, so if you are around, please come and join us. You can also watch the event via streaming at ASUOC's web site. I will be speaking at the event presenting Project Coin, NIO.2 and the Fork/Join Framework.

The information of my presentation is as follows:

WhereICESI University
Auditorio Varela S.A.
Cali, Colombia
WhenSeptember 13th 2012
16:00 - 17:30 (GMT-5)

More info (in spanish):

Colombia Oracle Users Group
ICESI University

See ya!