Design Patterns In Java
My personal opinion is that Gang of Four is good for academic purposes (only), or as a theoretical reference. The best advice I have received from architects in my company with 20+ years of development experience: 1. The best designers are the on. Java Design Patterns 1 / 173 Chapter 1 Introduction to Design Patterns 1.1Introduction In the late 70’s, an architect named Christopher Alexander started the concept of patterns. Alexander’s work focused on finding patterns of solutions to particular sets of forces within particular contexts.
Design Patterns are very popular among software developers. A design pattern is a well-described solution tocommon software problem.
Some of benefits of using design patterns are :
- Design patterns are already defined and provides industry standard approach to solve recurring problem,so it saves time if we use the design pattern .
- Using design pattern promotes re-usability that leads to more robust and highly maintainable code.
- Since design patterns are already defined, it makes out code easy to understand and debug. It lead to faster development and new members of team understand it easily.
What is a Design Pattern ?
A software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design --- Wikipedia
Java Design Patterns are divided into tree parts : Creational, Structural and Behavioral.
CREATIONAL DESIGN PATTERNS
Creational design pattens provide solution to instantiate an object in the best possible way for specific situations.The basic form of object creation could result in design problems or add unwanted complexity to the design. Creational design patterns solve this problem by controlling the object creation by different ways.There are five creational design patterns that we will discuss on :
- Singleton Pattern
- Factory Pattern
- Abstract Factory Pattern
- Builder Pattern
- Prototype Pattern
Pattern Singleton
Pattern Singleton: > One Class, one Instance.
Singleton is one of the Gangs of Four Design patterns and comes in the Creational Design Pattern category.Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the Java virtual machine. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, driver objects, caching and thread pool. Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc. Singleton design pattern is used in core Java classes also, for example java.lang.Runtime , java.awt.Desktop.
To implement Singleton pattern, there are really many approaches but all of them have following common concepts:
- A private constructor to avoid instantiation of the class,
- A private static variable from the same class that's the only instance of the class.
- public static method that returns the instance of the class, this is the global access point for the outer world toget the instance of the class.
We'll implement the thread safe one here. Classes are in the package com.singleton
;
Pattern Factory
Factory design pattern is used when we have a super class with multiple sub-classes and based on input, we need to return one of the sub-class. This pattern take out the responsibility of instantiation of a class from client program to the factory class. Let’s first learn how to implement factory pattern in Java and then we will learn its benefits and we will see its usage in JDK.
- Super Class : Super class in factory pattern can be an interface, abstract class or a normal Java class. For our example, we have super class as abstract class with overridden toString() method for testing purpose.see
com.factory
. - sub-classes: Let’s say we have two sub-classes PC and Server with implementation in
com.factory
Here's what we have in image :
Now let's write the test class.
This pattern provides some advantages such as :
- It provides approach to code for the interface rather than the implementation.
- It removes the instantiation of the actual implementation classes from client code, making it more robust.
- It provides abstraction between implementation and client classes through inheritance.
As examples of its implementation in JDK we have :
- java.util.Calendar, ResourceBundle() and NumberFormat getInstance();
- valueOf() method in wrapper classes like Boolean , Integer etc.
Architectural Design Patterns In Java
Abstract Factory
This is one of the Creational Pattern and almost similar to Factory Pattern except the fact that it's most likeFactory of factories. If you're familiar with factory design pattern in java , you'll notice that we have a single Factory class that returns the different sub-classes based on the input provided and the factory class uses if-else or switch statement to achieve this. Like our factory pattern post, we will use the same super class and sub-classes.Codes are available in com.abstractFactory
.Here's the implementation of the test class:
Pattern Builder
Builder pattern is a creational design pattern as Factory Pattern and Abstract Factory Pattern. This pattern was introduced to solve some of the problems with Factory and Abstract Factory patterns when the Object contains a lot of attributes. This pattern deals with a static nested class and then copy all the arguments from the outer class to the Builder class.The sample code where we have a Computer class and ComputerBuilder to build it are available in the package com.builder.Computer
.Here's a test program showing how to use Builder class to get object.
There are really various implementations of this pattern in JDK : java.lang.StringBuilder#append() (unsynchronized) java.lang.StringBuffer#append() (synchronized) .
Pattern Prototype
Prototype pattern is one of the Creational Design pattern, so it provides a mechanism of object creation. Prototype pattern is used when the Object creation is a costly affair and requires a lot of time and resources and you have a similar object already existing. So this pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs. This pattern uses Java cloning to copy the object.
Here's the program that will show the benefit of the Prototype pattern usage.
STRUCTURAL DESIGN PATTERNS
Structural Patterns provide different ways to create a class structure, for example using inheritance and compositionto create a large object from small objects.
Adapter Pattern
This pattern is used in such a way that two unrelated interfaces can work together. The object that joins these unrelated interfaces is called Adapter. As a real life example, we can think of a mobile charger as an adapter because mobile battery needs 3 Volts to charge but the normal socket produces either 120V (US) or 240V (India). So the mobile charger works as an adapter between mobile charging socket and the wall socket.First of all we'll have two classes : Volt - to measure volts) and Socket :
Now we want to build an adapter that can produce 3 volts, 12 volts and default 120 volts. So first of all we will create an adapter interface with these methods.
while implementing this pattern, there are two approaches : one that deals with inheritance and another one that deals with Composition. Note that they are almost the same thus, here we'll deal with one with inheritance. Let's implement out adapter class !
Now let's see how all this work ! Here's a test Main function to illustrate.
This pattern has many usage in the JDK :
Design Patterns In Java 8
- java.util.Arrays#asList() java.io.InputStreamReader(InputStream) (returns a Reader),
- java.io.OutputStreamWriter(OutputStream) (returns a Writer).
Design Patterns In Java Dzone
Composite Pattern
Comments are closed.