Posts

Showing posts with the label design patterns

Understanding Immutable Classes In Java

I recently reviewed an article that claimed immutable classes in Java are not always thread safe. Ultimately, this is not true since any immutable class cannot contain state and therefore no two threads could change it's state. To understand this more, I would like to do a quick dive into what an Immutable class is in Java.

The Java Enum: A Singleton Pattern

Image
The singleton pattern restricts the instantiation of a class to one object. In Java, to enforce this, the best approach is to use an enum. This great idea comes straight from the book Effective Java by Joshua Bloch. If you don't have it in your library, get it. One of the best Java books to date. There are a few reasons why one would use an enum as a singleton in Java:

Applying the Strategy Pattern in Java

Image
Working with strategy on Arrays.sort & java.util.Comparator All these examples and more can be found on github In Java, you cannot pass function references through a method. With this being true, how do we then apply a strategy to a method? What is suggested, is that we define an interface with the function we want to pass. This way we can on the fly, define and pass an algorithm to a method for process. In this demo, we will be working strictly with the strategy interface:   java.util.Comparator . This is a java strategy interface, readily available in the Java API as of 1.5. It supplies a compare algorithm, where its implementation is primarily for sorting large collections of objects.