
Strategy pattern is very useful for implementing a family of algorithms. It is a behavioral design pattern.
With Strategy pattern we can select the algorithm at runtime. We can use it to select the sorting strategy for data. We can use it to save files in different formats like- .txt, .csv, .jpg etc.
In Observer design pattern, there is a Subject that maintains the list of Observers that are waiting for any update on the Subject. Once there is an update in Subject it notifies all the observers for the change.
E.g. In real life, students are waiting for the result of their test. Here students are the observers and test is the subject. Once the result of test is known, testing organization notifies all the students about their result.
The most popular use of Observer pattern is in Model View Controller (MVC) architectural pattern.
Main issue with Observer pattern is that it can cause memory leaks. The subject holds a strong reference to observers. If observers are not de-registered in time, it can lead to memory leak.
State design pattern is a behavioral design pattern that is use for defining the state machine for an object. Each state of an object is defined in a child class of State class. When different actions are taken on an Object, it can change its state.
Strategy pattern is also a behavioral pattern, but it is mainly used for defining multiple algorithms. With same action of a client, the algorithm to be used can change.
Some people consider State pattern similar to Strategy pattern, since an Object changes its Strategy with different method invocations. But the main difference is that in State pattern internal state of an Object is one of the determining factors for selecting the Strategy for change of state.
Where as in Strategy pattern, client can pass some external parameter in input during method invocation that determines the strategy to be used at run time.
Therefore State pattern is based on the Object’s internal state, where as Strategy pattern is based on Client’s invocation.
State pattern is very useful in increasing the maintainability of the code in a large code-base.
Some people call Decorator pattern as Wrapper pattern as well. It is used to add the behavior to an object, without changing the behavior of other objects of same class.
One of the very good uses of Decorator pattern is in java.io package. We can have a FileInputStream to handle a File. To add Buffering behavior we can decorate FileInputStream with BufferedInputStream. To add the gzip behavior BufferedInputStream we can decorate it with GzipInputStream. To add serialization behavior to GzipInputStream, we can decorate it with ObjectInputStream.
Some of the good scenarios where Composite design pattern can be used are as follows:
Tree Structure: The most common use of Composite design pattern is Tree structure. If you want to represent data in a Tree data structure, Composite pattern can be used.
E.g. In an Organization, to a Manager has Employees. But Manager is also an Employee. If we start from CEO level, there is one big tree for the whole organization structure. Under that big tree there are many sub-trees. This can be easily represented with Composite design pattern.
Recursion: Another use of Composite design pattern is Recursion. If we have a Recursion based algorithm, we need data to be passed to algorithm in a data structure that treats individual objects and compositions at each level of recursion uniformly.
E.g. To implement a recursive Polynomial Solving algorithm, we can use Composite design pattern to store the intermediate results.
Graphics: Another good use of Composite design pattern is in Graphics. We can group shapes inside a composite and make higher-level groups of smaller groups of shapes to complete the graphics to be displayed on screen.
Yes. Singleton is one of the most popular design patterns in enterprise level Java applications. Almost in every project we see some implementation of Singleton.
With Singleton pattern we can be sure that there is only one instance of a class at any time in the application.
This helps in storing properties that have to be used in the application in a unique location.
In Java, java.lang.Runtime is implemented on Singleton design pattern.
Runtime is the class that acts as an interface with the environment in which Java process is running. Runtime contains methods that can interact with the environment.
Like- totalmemory() method gives the total memory in JVM. maxMemory() method gives the maximum memory that JVM can use.
There is an exit() method to exit the Java process. We do not want multiple objects in JVM to have exit() method.
Similarly there is gc() method that can run the Garbage Collector. With only one copy of gc() method, we can ensure that no other object can run the Garbage Collector when one instance of GC is already running.
In Java there are many options to implement a thread-safe Singleton pattern. Some of these are as follows:
Sample code:
class DoubleCheckSingleton {
private volatile HelloSingleton helloSingleton; // Use Volatile
public HelloSingleton getHelloSingleton() {
HelloSingleton result = helloSingleton;
if (result == null) {
synchronized(this) { // Synchronize for thread safety
result = helloSingleton;
if (result == null) {
result = new HelloSingleton();
helloSingleton = result;
}
}
}
return result;
}
}
Sample code:
public class SingletonBillPugh {
// Inner class that holds instance
private static class InnerSingleton{
private static final SingletonBillPugh INSTANCE = new SingletonBillPugh();
}
// Private constructor
private SingletonBillPugh(){}
public static SingletonBillPugh getInstance(){
return InnerSingleton.INSTANCE;
}
}
When first time SingletonBillPugh is loaded in memory, InnerSingleton is not loaded. Only when getInstance() method is called, InnerSingleton class is loaded and an Instance is created.
Sample Code:
public enum SingletonEnum {
INSTANCE;
public static void doImplementation(){
…..
}
}
It is a behavioral design pattern. We can use it to create an outline for an algorithm or a complex operation. We first create the skeleton of a program. Then we delegate the steps of the operation to subclasses. The subclasses can redefine the inner implementation of each step.
E.g. While designing a Game in Java, we can implement it as an algorithm with Template Method pattern. Each step in the game can be deferred to subclasses responsible for handling that step.
Let say we implement Monopoly game in Java. We can create methods like initializeGame(), makeMove(), endGame() etc. Each of these methods can be handled in subclasses in an independent manner.
We can use same algorithm for Chess game with same set of abstract methods. The subclass for Chess game can provide the concrete implementation of methods like initializeGame(), makeMove(), endGame() etc.
Template Method pattern is very useful in providing customizable class to users. We can create the core class with a high level implementation. And our users can customize our core class in their custom subclasses.
Factory Method pattern is a creational design pattern. A Factory is an object that is used to create more objects.
In general, a Factory object has methods that can be used to create a type of objects. Some people call it Factory Method design pattern as well.
Some of the examples of Factory Method pattern in JDK are:
By using Static Factory Method we encapsulate the creation process of an object. We can use new() to create an Object from its constructor. Instead we use static method of a Factory to create the object. One main advantage of using Factory is that Factory can choose the correct implementation at runtime and create the right object. The caller of method can specify the desired behavior.
E.g. If we have a ShapeFactory with createShape(String type) method. Client can call ShapeFactory.createShape(“Circle”) to get a circular shape. ShapeFactory.createShape(“Square”) will return square shape. In this way, ShapeFactory knows how to create different shapes based on the input by caller.
Another use of Factory is in providing access to limited resources to a large set of users.
E.g. In ConnectionPool, we can limit the total number of connections that can be created as well as we can hide the implementation details of creating connection. Here ConnectionPool is the factory. Clients call static method ConnectionPool.getConnection().
In JDK there are many places where Builder design pattern is used. Some of these are as follows:
In JDK there are many places where Abstract Factory design pattern is used. Some of these are as follows:
In JDK there are many places where Decorator design pattern is used. Some of these are as follows:
Proxy design pattern provides an extra level of indirection for providing access to another object. It can also protect a real object from any extra level of complexity.
In JDK there are many places where Proxy design pattern is used. Some of these are as follows:
In JDK there are many places where Chain of Responsibility design pattern is used. Some of these are as follows:
Command design pattern is a behavioral design pattern. We use it to encapsulate all the information required to trigger an event. Some of the main uses of Command pattern are:
In JDK there are many places where Command design pattern is used. Some of these are as follows:
Interpreter design pattern is used to evaluate sentences in a language. E.g. In SQL we can use it to evaluate a query by evaluating each keyword like SELECT, FROM, WHERE clause.
In an Interpreter implementation there is a class for each keyword/symbol. A sentence is just a composite of these keywords. But the sentence is represented by Syntax tree that can be interpreted.
In JDK there are many places where Interpreter design pattern is used. Some of these are as follows:
By using Mediator pattern we can decouple the multiple objects that interact with each other. With a Mediator object we can create many-to-many relationships in multiple objects.
In JDK there are many places where Mediator design pattern is used. Some of these are as follows:
In JDK there are many places where Strategy design pattern is used. Some of these are as follows:
By using Visitor design pattern we can add new virtual methods to existing classes without modifying their core structure.
In JDK there are many places where Visitor design pattern is used. Some of these are as follows:
Main differences between Decorator and Proxy design pattern are:
We use Setter injection to provide optional dependencies of an object. Constructor injection is used to provide mandatory dependency of an object.
In Spring IoC, Dependency Injection is heavily used. There we have to differentiate between the scenario suitable for Setter based and Constructor based dependency injection.
Proxy design pattern can be used in a wide variety of scenario in Java. Some of these are as follows:
Adapter pattern provides a different interface to an object. But the Proxy always provides same interface to the object.
Adapter is like providing an interface suitable to client’s use. But Proxy is same interface that has additional feature or check.
E.g. In electrical appliances we use Adapter to convert from one type of socket to another type of socket. In case of proxy, we have a plug with built-in surge protector. The interface for plug and the original device remains same.
If we have two classes with incompatible interfaces, we use Adapter pattern to make it work. We create an Adapter object that can adapt the interface of one class to another class.
It is generally used for working with third party libraries. We create an Adapter class between third party code and our class. In case of any change in third party code we have to just change the Adapter code. Rest of our code can remain same and just take to Adapter.
In JDK there are many places where Adapter design pattern is used. Some of these are as follows:
With Factory design pattern we can create concrete products of a type that Factory can manufacture. E.g. If it is CarFactory, we can produce, Ford, Toyota, Honda, Maserati etc.
With Abstract Factory design pattern we create a concrete implementation of a Factory. E.g. DeviceFactory can be Abstract and it can give us GoogleDeviceFactory, AppleDeviceFactory etc. With AppleDeviceFactory we will get products like- iPhone, iPad, Mac etc. With GoogleDeviceFactory we will get products like- Nexus phone, Google Nexus tablet, Google ChromeBook etc.
So it is a subtle difference between Factory and Abstract Factory design pattern. One way to remember is that within Abstract Factory pattern, Factory pattern is already implemented.
Open/closed design principle states “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”.
Open/closed principle term was originated by Bertrand Meyer in his book Object Oriented Software Construction.
As per this principle, if a module is available for extension then it is considered open. If a module is available for use by other modules then it is considered closed.
Further Robert C. Martin has mentioned it as O in SOLID principles of Object Oriented design.
It is used in State and Strategy design patterns. Context class is closed for modification. But new functionality can be added by writing new strategy code.
SOLID word in SOLID design principle is an acronym for:
Builder design pattern is a creational design pattern. We can use Builder pattern to create complex objects with multiple options.
E.g. when we have to create a Meal in a restaurant we can use Builder pattern. We can keep adding options like- Starter, Drink, Main Course, and Dessert etc. to create complete meal. When a user selects other options of Starter, Drink Main Course, Dessert another type of meal is created.
Main feature of Builder pattern is step-by-step building of a complex object with multiple options.
In Object Oriented design mainly three categories of design patterns are used. These categories are:
We can use Iterator design pattern to access the individual elements of a Collection. In case of an ordered collection we can get Iterator that returns the elements in an order.
In Java there are many implementation of Iterator in Collections package. We have iterators like- Spliterator, ListIterator etc. that implement Iterator pattern.
We can use BlockingQueue in Java to implement Producer Consumer design pattern.
It is a concurrent design pattern.
We can use Decorator design pattern to add new features to an existing object. With a Decorator we work on same object and return the same object with more features. But the structure of the object remains same since all the decorated versions of object implement same interface.
We can use Bridge design pattern to detach the implementation from the abstraction.
Bridge is mainly used for separation of concern in design. We can create an implementation and store it in the interface, which is an abstraction. Where as specific implementation of other features can be done in concrete classes that implement the interface.
Often Bridge design pattern is implemented by using Adapter pattern.
E.g. we have Shape interface. We want to make Square and Circle shapes. But further we want to make RedSquare, BlackSquare shapes and GreenCircle, WhiteCircle shapes. In this case rather than creating one hierarchy of all the shapes, we separate the Color concern from Shape hierarchy.
So we create two hierarchies. One is Shape to Square and Shape to Circle hierarchy. Another one is Color to Red, Black, Green, White hierarchy. In this way we can create multiple types of shapes with multiple colors with Bridge design pattern.
Android applications predominantly use Model View Presenter design pattern.
First we should not implement the Cloneable interface by the object that is a Singleton.
Second, if we have to implement Cloneable interface then we can throw exception in clone() method.
This will ensure that no one can use clone() method or Cloneable interface to create more than one instance of Singleton object.
Architectural patterns are used to define the architecture of a Software system. Some of the patterns are as follows:
Some of the popular uses of Façade design pattern are as follows:
Both Factory and Builder patterns are creational design patterns. They are similar in nature but Factory pattern is a simplified generic version of Builder pattern.
We use Factory pattern to create different concrete subtypes of an Object. The client of a Factory may not know the exact subtype. E.g. If we call createDrink() of a Factory, we may get Tea or Coffee drinks.
We can also use Builder pattern to create different concrete subtypes of an object. But in the Builder pattern the composition of the object can be more complex. E.g. If we call createDrink() for Builder, we can getCappuccino Coffee with Vanilla Cream and Sugar, or we can get Latte Coffee with Splenda and milk cream.
So a Builder can support creation of a large number of variants of an object. But a Factory can create a broader range of known subtypes of an object.
E.g. One good use of memento is in online Forms. If we want to show to user a form pre-populated with some data, we keep this copy in memento. Now user can update the form. But at any time when user wants to reset the form, we use memento to make the form in its original pre-populated state. If user wants to just save the form we save the form and update the memento. Now onwards any new changes to the form can be rolled back to the last saved Memento object.
An AntiPattern is opposite of a Design Pattern. It is a common practice in an organization that is used to deal with a recurring problem but it has more bad consequences than good ones.
AntiPattern can be found in an Organization, Architecture or Software Engineering.
Some of the AntiPatterns in Software Engineering are:
DAO design pattern is used in the data persistent layer of a Java application. It mainly uses OOPS principle of Encapsulation.
By using DAO pattern it makes the application loosely coupled and less dependent on actual database.
We can even implement some in-memory database like H2 with DAO to handle the unit-testing.
In short, DAO hides the underlying database implementation from the class that accesses the data via DAO object.
Recently we can combine DAO with Spring framework to inject any DB implementation.
Java Design Patterns is a very important topic in technical interview. Many fortune 500 organizations use Design Patterns. Big companies like Amazon, Netflix, Google etc use Java Design Patterns based architecture. This course is designed to help you answer interview questions on Java Design Patterns.
Software Engineers with Java Design Patterns knowledge may get more salary than others with similar qualifications without Java Design Patterns knowledge.
In this course, you will learn how to handle interview questions on Java Design Patterns in Software Design and Development. We will explain you the important concepts of Java Design Patterns.
You will also learn the benefits and use cases of Java Design Patterns in this course.
What is the biggest benefit of this course to me?
Finally, the biggest benefit of this course is that you will be able to demand higher salary in your next job interview.
It is good to learn Java Design Patterns for theoretical benefits. But if you do not know how to handle interview questions on Java Design Patterns, you can not convert your Java Design Patterns knowledge into higher salary.
What are the topics covered in this course?
We cover a wide range of topics in this course. We have questions on Java Design Patterns best practices, Factory, Singleton, Proxy Design Pattern etc.
How will this course help me?
By attending this course, you do not have to spend time searching the Internet for Java Design Patterns interview questions. We have already compiled the list of the most popular and the latest Java Design Patterns Interview questions.
Are there answers in this course?
Yes, in this course each question is followed by an answer. So you can save time in interview preparation.
What is the best way of viewing this course?
You have to just watch the course from beginning to end. Once you go through all the videos, try to answer the questions in your own words. Also mark the questions that you could not answer by yourself. Then, in second pass go through only the difficult questions. After going through this course 2-3 times, you will be well prepared to face a technical interview in Java Design Patterns.
What is the level of questions in this course?
This course contains questions that are good for a Fresher to an Architect level. The difficulty level of question varies in the course from a Fresher to an Experienced professional.
What happens if Java Design Patterns technology changes in future?
From time to time, we keep adding more questions to this course. Our aim is to keep you always updated with the latest interview questions on Java Design Patterns.
What are the sample questions covered in this course?
Sample questions covered in this course are as follows: