Design Patterns in Java

Design Patterns in Java

Tutorial Details
  • Topic: Design Patterns/Java
  • Difficulty: Beginner
  • Estimated Completion Time: 45 minutes

One of the unchanging facts of life is that change is the undying constant in every software lifecycle – one that you cannot run away from. The challenge is to adapt to this change with minimum latency and maximum flexibility.

The good news is that someone has probably already solved your design problems and their solutions have evolved into best practices; these agreed-upon best practices are referred to as “Design Patterns”. Today, we’re going to explore two popular design patterns, and learn how good design can help you write code that is squeaky clean and extensible.


The Adapter Design Pattern

Let’s assume that you have an existing legacy system. You’re now tasked with making it work with a new third-party library, but this library has a different API compared to the last one you were using. The legacy system now expects a different interface than what the new library provides. Of course, you could be brave (read, foolish) enough to think about changing your legacy code to adapt to new interface but as with every legacy system — never, ever.

Incompatible Interfaces

Adapters to the rescue! Simply write an adapter(a new wrapping class) in between the systems, which listens for client requests to the older interface, and redirects or translates them into calls to the new interface. This conversion can either be implemented with inheritance or composition.

Great design is not just about re-usability, but about extensibility.

Adapters help incompatible classes work together by taking an interface and adapting it to one that the client can parse.

Adapters to the Rescue !!

Adapters In Action

Enough chit-chat; let’s get down to business, shall we? Our legacy software system uses the following LegacyVideoController interface to control the video system.

	public interface LegacyVideoController{

		/**
		 * Begins the playback after startTimeTicks 
		 * from the beginning of the video
		 * @param startTimeTicks time in milliseconds
		 */
		public void startPlayback(long startTimeTicks);
		...
	}

The client code which uses this controller looks like:

	public void playBackVideo(long timeToStart, LegacyVideoController controller){
		if(controller!=null){
			controller.startPlayback(timeToStart);
		}
	}

User Requirements Change!

There’s nothing new here, really – it happens quite frequently. User requirements are prone to change all the time and our legacy system now needs to work with a new video controller, having the following interface:

	public interface AdvancedVideoController{
		/**
		 * Places the controller head after time 
		 * from the beginning of the track
		 * @param time time defines how much seek is required
		 */
		public void seek(Time time);

		/**
		 * Plays the track
		 */
		public void play();
	}

As a result, the client code breaks, as this new interface is not compatible.

Adapter Saves the Day

So, how do we handle this modified interface without changing our legacy code? You know the answer now, don’t you? We write a simple adapter to modify its interface to adapt to the existing one as below:

	public class AdvancedVideoControllerAdapter implements LegacyVideoController {
	
		private AdvancedVideoController advancedVideoController;
		
		public AdvancedVideoControllerAdapter(AdvancedVideoController advancedVideoController){
			this.advancedVideoController = advancedVideoController;
		}

		@Override
		public void startPlayback(long startTimeTicks) {
			
			// Convert long into DateTime
			Time startTime = getTime(startTimeTicks);
			
			// Adapt
			advancedVideoController.seek(startTime);
			advancedVideoController.play();
		}
	}

This adapter implements the target interface, which the client expects so there is no need to change the client code. We compose the adapter with an instance of the adaptee interface.

This “has-a” relationship allows the adapter to delegate the client request to the actual instance.

Adapters also help in decoupling the client’s code and the implementation.

We can now simply wrap the new object in this adapter and be done with it, without making any changes to the client code as the new object is now converted/adapted to the same interface.

	AdvancedVideoController advancedController = controllerFactory.createController();
	// adapt 
	LegacyVideoController controllerAdapter = new AdvancedVideoControllerAdapter(advancedController);
	playBackVideo(20, controllerAdapter);

An adapter can be a simple pass through or can be intelligent enough to provide some add-ons depending on the complexity of the interface to support. Similarly, one adapter can be used to wrap more than one object if the target interface is complex and the new functionality has been split across two or more classes.

Comparison With Other Patterns

  • Decorator : Decorator changes the interface and wraps an object around by adding new responsibility. On the other hand, adapter is used to convert the adaptee interface to target interface which is understood by the client.
  • Facade : Facade works by defining a totally new interface abstracting the complexity of earlier interfaces while adapter is used to enable communication between incompatible interfaces by converting one into another.
  • Proxy : Proxy provides the same interface. Whereas adapter provides a different interface to its subject.
  • Bridge : Bridge is designed upfront to let the abstraction and the implementation vary independently but adapter is used to adapt to an existing interface by delegating the request to adaptee.

The Singleton Design Pattern

Though there are many patterns which deal with creation of objects, one specific pattern stands out. Today we’re going to inspect one of the most simple, yet misunderstood, ones: the Singleton pattern.

As the name suggests, the purpose of the singleton is to create a single instance of the class and provide global access to it. Examples can be an application level Cache, an object pool of threads, connections etc. For such entities, one and only instance must suffice else they threaten the stability and defeat the purpose of the application.

Implementing the Singleton Pattern

A bare-bones implementation in Java would look like:

	public class ApplicationCache{
		
		private Map<String, Object> attributeMap;
		// Static instance
		private static ApplicationCache instance;

		// Static accessor method
		public static ApplicationCache getInstance(){
			if(instance == null){
				instance == new ApplicationCache();
			}
			return instance;
		}

		// private Constructor
		private ApplicationCache(){
			attributeMap = createCache(); // Initialize the cache
		}
	}

In our example, the class holds a static member of the same type as that of the class, which is accessed via a static method. We make use of Lazy Initialization here, delaying the initialization of the cache, until it is actually needed at runtime. The constructor is also made private so that a new instance of this class cannot be created using the new operator. To fetch the cache, we invoke:

	ApplicationCache cache = ApplicationCache.getInstance();
	// use cache to improve performance

It works perfectly fine as long as we are dealing with a single-threaded model. But life, as we know it, is not that simple. In a multi-threaded environment, you need to synchronize the lazy initialization or just do away with it, by creating the cache as soon as the class is loaded, either by using static blocks or initializing while declaring the cache.

Double Checked Locking

We synchronize the lazy initialization to make sure that the initialization code is run only once. This code works with Java version 5.0 and above due to idiosyncrasies associated with the implementation of synchronized and volatile in Java.

	public class ApplicationCache{
		
		private Map<String, Object> attributeMap;
		// volatile so that JVM out-of-order writes do not happen
		private static volatile ApplicationCache instance;

		public static ApplicationCache getInstance(){
			// Checked once
			if(instance == null){
				// Synchronized on Class level lock
				synchronized(ApplicationCache.class){
					// Checked again
					if(instance == null){
						instance == new ApplicationCache();
					}
				}	
			}
			return instance;
		}

		private ApplicationCache(){
			attributeMap = createCache(); // Initialize the cache
		}
	}

We make the instance variable volatile so that the JVM prevents out-of-order writes for it. We also do a double null check (hence the name) for instance while synchronizing the initialization so that any sequence of 2 or more threads does not corrupt the state or result in creation of more than one instance of the cache. We could have synchronized the whole static accessor method instead, but that would have been an overkill as synchronization is only needed until the object is fully initialized; never again while accessing it.

No Lazy Initialization

An easier way would be to do away with the benefits of lazy initialization, also resulting in cleaner code:

	public class ApplicationCache{
		
		private Map<String, Object> attributeMap;
		// Initialized while declaration
		private static ApplicationCache instance = new ApplicationCache();

		public static ApplicationCache getInstance(){
			return instance;
		}

		// private Construcutor
		private ApplicationCache(){
			attributeMap = createCache(); // Initialize the cache
		}
	}

As soon as the class loads and the variables are initialized, we invoke the private constructor to create the one and only instance of the cache. We lose the benefits of lazily initializing the instance but the code is much cleaner. Both methods are thread-safe and you can choose the one suitable for your project environment.

Safeguard Against Reflection and Serialization

Depending on your requirement, you might also want to protect against:

  • Code using Reflection API to invoke the private constructor, which can be dealt with by throwing an exception from the constructor, in case it is called more than one time.
  • Similarly serializing and de-serializing the instance might also result in two different instances of our cache, which can be handled by overriding the readResolve() method from the Serialization API

Design Patterns are Language Agnostic

The title of our tutorial is a bit misleading, I admit, as design patterns are really language-agnostic. They are simply a collection of the best design strategies developed to counter recurring problems faced in software design. Nothing more, nothing less.

For example, below is a quick look at how we could implement a singleton in Javascript. The intent remains the same: controlling the creation of the object and maintaining a global point of access, but the implementation differs with the constructs and semantics of each language.

	
	var applicationCache = function() {

		// Private stuff
		var instance;

		function initCache() {
			return {
				proxyUrl: "/bin/getCache.json",
				cachePurgeTime: 5000,
				permissions: {
					read: "everyone",
					write: "admin"
				}
			};
		}

		// Public
		return {
			getInstance: function() {
				if (!instance) instance = initCache();
				return instance;
			},
			purgeCache: function() {
				instance = null;
			}
		};
	};

To quote another example, jQuery also makes heavy use of the Facade design pattern, abstracting away the complexity of a subsystem and exposing a simpler interface to the user.


Closing Remarks

Not every problem requires the use of a specific design pattern

A word of caution is necessary: do not overuse! Not every problem requires the use of a specific design pattern. You need to carefully analyze the situation before settling on a pattern. Learning design patterns also helps in understanding other libraries like jQuery, Spring etc which make heavy use of many such patterns.

I hope that, after reading this article, you’re able to get a step closer in your understanding of design patterns. If you have any questions or want to learn additional design pattern, please let me know within the comments below, and I will do my best to answer your questions!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://tinker.kotaweaver.com Kota Weaver

    Nice article! I’d like to see more of these tutorials on Java, and more of these sorts of practical articles.

    Just a note, I believe there is a typo in “Implementing the Singleton Pattern” and “Double Checked Locking”:

    if (instance == null){
    instance == new ApplicationCache();
    }

    should be

    if (instance == null) {
    instance = new ApplicationCache();
    }

    • http://techno-cratic.blogspot.in/ Agraj Mangal
      Author

      Thanks Kota for pointing that out. Will get it corrected.

  • http://www.makemescript.nl Maik Diepenbroek

    A good brief explanation about design patterns, is there a reason that you left out for example dependency injection ?

    • http://techno-cratic.blogspot.in/ Agraj Mangal
      Author

      Hi Maik,

      I’m not sure I follow correctly, but if you are asking for “dependency injection” & “Inversion of control” (IOC), then yes I’ve left many others too ;)

      Would love to write another article on some other famous & misunderstood patterns.

  • Bhavani

    Good to see java stuff finally!!

    • http://javarevisited.blogspot.nl JP

      Indeed. But little bit disappointed with coverage of Singleton, It doesn’t mention about Enum which is most easy way to create Singleton and provides iron clad guaranteed on thread-safety and serialization. Could have been more though and better.

  • Adria

    Thank you for the tutorial. Looks awesome.

  • http://desulicious.wordpress.com Desu

    I like this tutorial. I hope there is Java Framework for next tutorial :)

    • cHEk

      I hope javaTuts+ will be the next channel ;)

      • Java Geek

        Yes, Me too

      • http://ww.permanaj.net Permana Jayanta

        +1 for javatuts+

      • Dean

        Why limit it to Java? There should be something more, like ‘OOPTuts+’. So many principles to teach which can be spread over a multitude of languages!

  • http://pixelfellow.com Saquib

    Thats great article, more on java web development, servlet and how to build dynamic website using Java series will be great !

    What you think guys :)

  • Matt L.

    I’m so happy to see a Java tut! There’s a lot of opportunity to cover great web frameworks like Play also.

    Keep ‘em comin!

    • Ivanhoe

      +1 for Java and another +1 for Play!

      It would be great to see those tuts

      • http://www.ingo-fahrentholz.com Ingo Fahrentholz

        +1

  • http://hyvaa.tistory.com hyvaa

    Thx!
    goooood stuff.

  • http://www.catch22marketing.com Cameron Clark

    Great Java Tut. If you’re interested in taking it to the next level I recommend this Java newsletter to anyone – http://www.javaspecialists.eu

    Thanks Agraj.

  • http://www.devsign.co.za Devsign Web Design and Web Development

    Awesome little article, I’m definitely bookmarking this.

  • http://specra.com/ Uday

    Ruby fine
    Python fine
    PHP fine

    But JAVA ? Really ?

    The fact that Net Tuts is mainly for freelancer web developers and that a small tiny negligible percentage of them use Java makes these tutorials unwelcome.

    I know I have the option of not reading JAVA content on the blog, but if such posts continue to arrive in my email feed as well as my feed reader, I think I’ll have to pass on the Net tuts subscription.

    • http://www.jeffrey-way.com Jeffrey Way

      A little dramatic, don’t you think?

    • Ghouzu

      I think you’re letting your dislike of Java blind you to what this article really provides: design patterns.

      Read them as pseudo-code if the word Java offends, but don’t hate on design patterns. Besides, Java is as web development capable of any of the languages you’ve listed. Great article.

      • Dean

        Completely agree! This article is about “Design patterns”, not Java. Java has only been used as an example language to present the concept.

        I think far too many people take the written code for gospel, and if it isn’t in a language they are currently using disregard the true nature of the lesson being taught. Design patterns are fundamental to understanding why things are done a certain way, and how that way came about.

    • mark

      dont be a drama queen….if you dont want to follow net tuts no one is stopping u…

  • Rajiv

    Nice to see some Java stuff at last !!

    Can you please cover other patterns like Observer ?

  • Raghavan Mohan

    Good tutorials on Java. Like to see more Java tutorials in this site. :)

  • damith

    Great tutorial. We’r waiting for Java based framwork tutorials (Spring, Struts)

  • Jon

    Yes! More Java please. I haven’t even looked at it since leaving college and have been feeling guilty about that ever since. Would love to get back into to it and find out what is current through some more Tuts like this,

  • Malhotra

    Great info on patterns. Like everyone else, +1 for more java stuff !!

  • CodeWarrior2000

    Very much needed Java tutorial for all of us. However, doesn’t the client code really get changed anyway if the code is updated to refer to the new classes AdvancedVideoController and AdvancedVideoControllerAdapter?

    • http://techno-cratic.blogspot.in/ Agraj Mangal
      Author

      Agree that some minimal changes are to be made to client code, but they are additive in nature !!

      Since the client code is coupled with the interface ( LegacyVideoController ) rather than the implementation, and the new adaptor ( AdvancedVideoControllerAdapter ) implements the same interface, so we only introduce a new class and wrap the new video controller ( AdvancedVideoController ) into the legacy interface using the adaptor.

      We only change the way the new controller is created. All the method calls on that controller remains unchanged. Using the factory pattern, you can also abstract this creation mechanism into a different class, thereby encapsulating the change to a single class.

  • trix
  • http://atinder.com atinder

    good to see some java stuff here :)

  • http://www.ingo-fahrentholz.com Ingo Fahrentholz

    Yeah. Would be great if there will be Java (finally).

  • http://toefel.nl/ Christophe Hesters

    Nice post. One addition to the singleton pattern:

    According to Effective Java, item 4 (by Joshua Bloch, chief java architect at Google) a single element Enum is the best way to implement the singleton pattern in java. It guards against reflective instantiation and provides serialization machinery for free.

    public enum Singleton {
    INSTANCE;

    /*your class variables, methods, etc. */
    }

  • http://www.vedicrishi.in Chandan

    Finally JAVA stuff on net tuts .. nicely explained… :-)

    Waiting for many more on android and JAVA stuffs…

  • Nikolay

    An error in the Singleton, in the static method getInstance():
    instance == new ApplicationCache();

    it must be with only one = :
    instance = new ApplicationCache();

  • David

    Would be great to see a tut on Java Web Development

  • http://www.metacrash.com.au Marc Loney

    It’s really great to see design patterns being discussed, even if it’s in a language slightly foreign to alot of the developers around here! Alot of the Nettuts+ tutorial focus on introductory web development topics, so it’s nice to see tutorials like this branching out into some really important territory for newbies looking to take that next step.

    Well done!

  • Isabelle

    thumbs up! java! love it! and it’s industry standard…. more please ;-)

  • Tom

    Not sure why anyone would be upset with seeing java code here.. I mean really? You should not really care about the language. It really is arbitrary. You should be able to read source from any language and identify the implied pattern involved or apply a pattern to any language.

    On the flip side, not sure why people are also saying “great java tutorial”, etc lol. It’s not a java tutorial

    -_-

    “Design Patterns are Language Agnostic”

  • Diego

    Hey, interesting article.I have a question about java.

    where does it stand in the web developement world right now. and does it has any advantages over say, php or ruby ?

  • http://twitter.com/Digital_Misfit Jim J

    Glad to see some Java tuts finally making their way to NetTuts! Java is a very powerful language and is used in a lot of things. It’s a good language for people to learn, and it’s easy enough to learn as well. Would like to see some uses of deploying Java to do heavy lifting for PHP applications. Keep up the great work!

    And for anyone who doesn’t like seeing this Java article, just ignore it.

  • sajay

    Good to see java tutorials here finally, that wrap up pretty much everything related to web development

  • http://onetutorials.blogspot.com/ anu

    the great tutorial

  • Arthur

    GoF copy paste, and they’re not even mentioned.

  • Dimitry

    Dear Agraj, thanks for the article, yet, one thing confuses me. Could you please clarify here this line of code in the adapter class:

    private AdvancedVideoController advancedVideoController;

    Given that AdvancedVideoController is an interface (as seen in the code prior to this) and not a class, can we still create the object (although here it is the member of the class, yet it seems to me that it doesn’t matter) of the interface? I guess we can’t, at least it is definitely so in C#, and the same thing I was tought about Java when I learned it. There can’t be object of an interface, or not? So please clarify if we can create the object of an interface in this particular case and if we can, why?

    Thanks in advance!

    • Dimitry

      It seems that I got it, so the interface can be used here in such a way because we’re not creating the object itself, but rather we provide something like the template here. And it seems that this can also be done in C#, shame on me – coding with C# for more than 5 years and do not know it yet :( Since C# and Java are quite similar, could somebody share some link where this moment is clarified be it Java or C# – doesn’t matter. I need so badly to deal with this topic and yet I do not find it in any of my C# desktop books…

    • Dimitry

      It seems that I got it at last. It’s not an object, in this context it seems to be just the link to any object whose class implements a particular interface or inherits some abstract class. Was non-trivial for me. Please somebody correct me if I’m wrong here.

  • http://markoj.tumblr.com Marko Jozic

    You have to synchronize the code before the if-statement

    // thread 1 & 2 start here
    if(instance == null){
    // thread 1 has entered the if-block while thread 2 still waits before the block
    synchronized(ApplicationCache.class){
    // unfortunately thread 2 enters the if-block before thread 1 enters the lock
    if(instance == null){
    instance == new ApplicationCache();
    }
    }
    }
    }

    In this case the function will return the same instance .. but it will create an unreferenced Object into the memory … and because java has (also like .NET) Garbage-Collector we cannot (well it’s possible but …)
    control when this object will be removed from the RAM

    • http://markoj.tumblr.com Marko Jozic

      ps … sorry for the formatting
      I don’t know why my white-space has been deleted :S

      aaaaand I also don’t know how I can format my code in the comment-block properly :-)

    • http://techno-cratic.blogspot.in/ Agraj Mangal
      Author

      That’s why we have checked twice for the instance being null. In your example, when unfortunately the thread2 acquires the lock before the thread1. It agains check for the instance being null and only when its null, it creates the instance. Now it goes out and releases the lock. So that thread1 can acquire the lock. Now when thread1 will check the instance variable, it won’t be null and hence a second instance of the same will not be created.

      In a nutshell, only one thread will be allowed inside the synchronized block at a time and the first one to enter will create the instance and any thread after that will simply bypass the creation by checking for null again.

      Let me know if its not clear still

      Thanks,
      Agraj

  • http://websitezombie.com gusti

    +1 for javatuts ;D

  • sarabjeet

    i really like that you are giving information on core and advance java concepts. Being enrolled at http://www.wiziq.com/course/1779-core-and-advance-java-concepts i found your information very helpful indeed.thanks for it.

  • http://java67.blogspot.fr Java Rohi

    Great to see design pattern tutorials on my favorite tutorial site net.tutsplus. Love to read more on this topic from experts. Some of the concept like double checked locking helped me to understand some good concept on Singleton.

  • Rohit5

    Singleton is probably one of the another design pattern which, I would like to add in this list, especially when you use Enum as Singleton, as shown here http://javarevisited.blogspot.sg/2012/07/why-enum-singleton-are-better-in-java.html, it becomes easier to write and use.