Prev Next

Java / Design Patterns

1. What is design pattern in Java? 2. What is Observer design pattern in Java? 3. Name few design patterns used in standard JDK library in Java. 4. Explain strategy design pattern in Java. 5. Difference between Strategy and State design Pattern in Java. 6. Singleton pattern. 7. How to implement a singleton pattern? 8. Why do we need Singleton class? (or) what are the advantages of using singleton pattern? 9. What is Decorator pattern in Java? 10. Give an example of Decorator pattern in Java. 11. Difference between Decorator and Proxy pattern in Java. 12. When to use Setter and Constructor Injection in Dependency Injection pattern? 13. Explain Composite design Pattern in Java. 14. Explain Front controller design pattern in Java/J2ee. 15. Explain MVC design pattern in J2EE. 16. How do you implement a thread-safe Singleton in Java? 17. What is the difference between factory and abstract factory pattern in Java? 18. Is Decorator an EJB design pattern in Java? 19. Explain Facade design pattern. 20. Types of Java Design patterns. 21. Name few Creational Patterns in Java. 22. Name some of the structural design patterns in Java. 23. Name some of the Behavioral design patterns in Java. 24. Explain Builder Design Pattern. 25. Explain Factory pattern in Java. 26. Difference between Service Provider Interface (SPI) and Application Programming Interface (API). 27. Explain Service Provider framework pattern. 28. Explain telescopic constructor pattern in Java. 29. Explain Java beans pattern. 30. Disadvantages of Java beans pattern. 31. Explain builder pattern in Java. 32. Disadvantage of Builder pattern. 33. When to use Builder design pattern? 34. In Java singleton, how do you prevent creating instance using reflection? 35. How do we ensure Singleton Design Pattern in a clustered Environment? 36. Difference between Singleton Pattern and static Class in Java. 37. Give example of singleton class from JDK. 38. When to use Static Class in place of Singleton in Java? 39. Explain Bridge design pattern in Java. 40. Explain prototype pattern in Java. 41. Explain Template method design Pattern in Java. 42. What is filter pattern in Java? 43. Explain Proxy design pattern in Java. 44. What is Adapter pattern in Java? 45. Difference between the Bridge and Adapter pattern in Java. 46. What is Chain of Responsibility Pattern in Java? 47. Explain Intercepting Filter pattern in Java. 48. Disadvantage of using factory pattern for object creation. 49. Which pattern provides greater abstraction than factory pattern? 50. Disadvantages of the singleton pattern. 51. Which classes are candidates of Singleton? 52. What is double checked locking in Singleton? 53. How to prevent creating another instance of Singleton using clone() method? 54. How to prevent creating another instance of Singleton during serialization? 55. Explain mediator pattern in Java. 56. Give few examples of Mediator Pattern in JDK. 57. Explain Command design pattern in Java. 58. What is State Design Pattern in Java? 59. When cloning an object is preferred over creating a new object in Java? 60. Name some of the design patterns that makes use of singleton pattern. 61. Explain Memento pattern in Java. 62. When do you use memento design pattern ? 63. Explain visitor pattern in Java. 64. What is value object design pattern? 65. What is Transfer object design pattern in Java? 66. Explain Service Locator design pattern in Java. 67. Mention some of the core J2EE design patterns. 68. Difference between Front Controller and View Helper in J2EE. 69. Advantages of Factory method design pattern. 70. What is a monolithic architecture? 71. Is template method pattern an example of Inversion of control? 72. Give an example of Template method pattern from JDK. 73. Disadvantages of Immutable class. 74. Types of messaging patterns.
Could not find what you were looking for? send us the question and we would be happy to answer your question.

What is design pattern in Java?

Design patterns are experimented, highly validated and achieved way to solve a particular design issues by various programmers/experts around the world. Design patterns are extension to code reuse.

Types of design patterns include creational, structural, and behavioral design patterns.

What is Observer design pattern in Java?

Observer design pattern is based on notifying the changes in the state of object to observers so that they can perform action related to the state change. An ideal example will be a stock exchange where changes in the stock price must be reflected in Views to show to public. Here stock object is subject while different views are Observers.

Name few design patterns used in standard JDK library in Java.
  • Decorator design pattern used in various Java IO classes,
  • Singleton pattern used in Runtime, Calendar and various other classes,
  • Factory pattern used along with various Immutable classes likes Boolean e.g. Boolean.valueOf
  • and Observer pattern used in Swing and other event listener frameworks.
Explain strategy design pattern in Java.

Strategy pattern is useful for implementing set of related algorithms for example, compression algorithms, filtering strategies etc. Strategy design pattern allows you to create Context classes, that uses Strategy implementation classes for applying business rules. This pattern follows open closed design principle and quite useful in Java.

One example of Strategy pattern from JDK is a Collections.sort() method and Comparator interface, which is a strategy interface and defines strategy for comparing objects. Because of this pattern, we don't need to modify sort() method (closed for modification) to compare any object, at same time we can implement Comparator interface to define new comparing strategy (open for extension).

Difference between Strategy and State design Pattern in Java.

State design pattern is used to define and mange state of object, while Strategy pattern is used to define a set of interchangeable algorithm and let's client to choose one of them. So Strategy pattern is a client driven pattern while Object can manage there state itself.

Singleton pattern.

Singleton pattern ensures that only one instance or object of a class exists with the application and make sure that instance is available globally so that there is no need to create new instance of course there is no way to create more than one object.

How to implement a singleton pattern?

Create a public class having a private constructor. Private constructor ensures that the object cannot be created outside of the class.

Create a private static variable of the type Class itself.

Create a public static method e.g. getInstance() that returns the reference of the static variable, if the static variable is null then create a object for the class.

package org.javatutorials.designpatterns;

//Step 1
public class SingletonPattern {

	//Step 2
	private static SingletonPattern mySingletonObj;

	private SingletonPattern() {

	}

	public static SingletonPattern getInstance() {

		if (mySingletonObj == null) {
			mySingletonObj = new SingletonPattern();

		}

		return mySingletonObj;
	}
}

Why do we need Singleton class? (or) what are the advantages of using singleton pattern?
  • Singleton class prevent creation of many objects to the class.
  • Object creation of that class could be time-consuming.
  • Objects that are used across the application be singleton as it is very convenient to maintain the state.
What is Decorator pattern in Java?

The decorator pattern (also known as Wrapper) is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting or modifying the existing behavior of other objects from the same class.

The Decorator is known as a structural pattern.

Give an example of Decorator pattern in Java.

Decorator pattern is another popular java design pattern question which is common because of its high usage in java.io package. BufferedReader and BufferedWriter are good example of decorator pattern in Java.

Difference between Decorator and Proxy pattern in Java.

Decorator pattern is used to implement functionality on already created object, while Proxy pattern is used for controlling access to object. Another difference between Decorator and Proxy design pattern is that, Decorator doesn't create object, instead it get object in it's constructor, while Proxy actually creates objects.

When to use Setter and Constructor Injection in Dependency Injection pattern?

Use Setter injection to provide optional dependencies of an object, while use Constructor injection to provide mandatory dependency of an object, without which it can not work.

Explain Composite design Pattern in Java.

Composite pattern is core Java design pattern, which allows you to treat both the whole and part of the object to treat in similar way. Client code that deals with the Composite or individual object doesn't differentiate on them, it is possible because Composite class also implement same interface as there individual part.

One of the good example of Composite pattern from JDK is JPanel class, which is both Component and Container. When paint() method is called on JPanel, it internally calls paint() method of individual components and let them draw themselves.

Explain Front controller design pattern in Java/J2ee.

The front controller design pattern provides a single handler for all the incoming requests for a resource in an application and then dispatches the requests to the appropriate handler for that type of request. The front controller may use other helpers API to achieve the dispatching mechanism.

ActionServlet in Struts 1 framework or Dispatchers in Struts 2 implements the Front controller design pattern.

Explain MVC design pattern in J2EE.

MVC (Model-View-Controller) is a J2EE design pattern that decouples data access logic and presentation from business logic. MVC is a software architecture pattern for developing web application.

Model represents the application data domain. Application business logic is contained within the model and is responsible for maintaining data.

View It represents the user interface, with which the end users communicates and the model data is presented and viewed.

The Controller reacts to the user input. It creates, populates the model and helps identify the relevant view.

How do you implement a thread-safe Singleton in Java?

There are multiple ways to write thread-safe singleton in Java.

  • using double checked locking,
  • by using static Singleton instance initialized during class loading.
  • using Java enum to create a thread-safe singleton class.

Using Java enum to create thread-safe singleton is the most simplest way.

What is the difference between factory and abstract factory pattern in Java?

Both Abstract Factory and Factory design patterns are creational design pattern and is used to decouple clients from creating object they need.

The difference is Abstract Factory pattern delegates its responsibility of instantiating the object to another object by composition while the Factory Method pattern utilize inheritance and depends on a subclass to handle the object instantiation.

Is Decorator an EJB design pattern in Java?

No. Decorator design pattern adds new behaviors without modifying the existing behaviours to an object which resembles AspectJ and not the EJB.

Explain Facade design pattern.

The Facade Pattern makes one single complex interface easier to use, using a Facade class. The Facade Pattern provides a unified interface to a set of interface in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

Types of Java Design patterns.

Java Design Patterns are divided into three categories: creational, structural and behavioral design patterns.

Name few Creational Patterns in Java.

Abstract Factory, Builder, Factory method, prototype and singleton are some of the creational design patterns.

Name some of the structural design patterns in Java.

Adapter, Bridge, Composite, Decorator,Flyweight, Facade and proxy are some of the structural design patterns.

Name some of the Behavioral design patterns in Java.

Chain of Responsibility, Iterator, Strategy, Template, Command, Observer, state and Mediator are some of the behavioral design patterns.

Explain Builder Design Pattern.

Builder pattern, a creational design pattern was introduced to solve some of the problems with Factory and Abstract Factory design patterns when the Object contains too many attributes.

The builder pattern is a design pattern that allows for the step-by-step creation of complex objects using the correct sequence of actions. The construction is controlled by a director object that only needs to know the type of object it is to create.

Explain Factory pattern in Java.

Factory pattern is one of the Creational Design Patterns.

Factory pattern is used to construct objects such that they can be decoupled from the implementing system. It states that 'define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses'.

Difference between Service Provider Interface (SPI) and Application Programming Interface (API).

An API describes the classes, interfaces, methods that you call and use to achieve a goal while SPI describes the classes,interfaces, methods that you extend and implement to achieve a goal.

In JDBC the Driver class is part of the SPI: If you simply want to use JDBC, you don't need to use it directly, but everyone who implements a JDBC driver must implement that class.

The Connection interface is both SPI and API: You use it routinely when you use a JDBC driver and it needs to be implemented by the developer of the JDBC driver.

Explain Service Provider framework pattern.

A service provider framework is a system in which multiple service providers implement a service, and the system makes the implementations available to its clients, decoupling them from the implementations.

There are 3 essential components of a service provider framework: a service interface, which providers implement; a provider registration API, which the system uses to register implementations, giving clients access to them; and a service access API, which clients use to obtain an instance of the service. The service access API typically allows but does not require the client to specify some criteria for choosing a provider. In the absence of such a specification, the API returns an instance of a default implementation. The service access API is the "flexible static factory" that forms the basis of the service provider framework.

An classic example of SPI is JDBC, where Connection acts as the service interface, DriverManager.registerDriver as provider registration API, DriverManager.getConnection as service access API, and Driver is the service provider interface.

Explain telescopic constructor pattern in Java.

In java there is no support for default values for constructor parameters.

Telescoping constructor comes to the rescue. A class has multiple constructors, where each constructor calls a more specific constructor in the hierarchy, which has more parameters than itself, providing default value for the extra parameters. The next constructor does the same until there is no left.

public Person(String firstName, String lastName) {
        this(firstName, lastName, null);
    }
 
    public Person(String firstName, String lastName, String description) {
        this(firstName, lastName, description, 0);
    }
 
    public Person(String firstName, String lastName, String description, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.description = description;
        this.age = age;
    }

Explain Java beans pattern.

Using JavaBeans pattern, you call a parameterless constructor to create the object and then call setter methods to set each required parameter and each optional parameter of interest as required.

private Person person1= new Person();
person1.setFirstName("Steve");
person1.setLastName("Jobs");
person1.setDescription("Apple Founder");

This is an alternative to the telescopic constructor pattern. Java beans pattern allows inconsistency and mandates mutability which is a drawback.

Disadvantages of Java beans pattern.
  • JavaBean will be in inconsistent state partway through its construction.
  • The JavaBeans pattern makes it impossible of making a class immutable.
  • It allows inconsistency and mandates mutability.
Explain builder pattern in Java.

Builder pattern combines the safety of the telescoping constructor pattern with the readability of the JavaBeans pattern.

To create the desired object, the client first calls a constructor (or static factory) with all of the required parameters and gets a builder object. Then the client calls setter-like methods on the builder object to set each optional parameter of interest. Finally, the client calls a parameter-less build method to generate the object, which is immutable.

The builder is a static member class of the class it builds.

public class BuilderPatternEx {

	static class Person {
		private String fName;
		private String lName;
		private short age;
		private String employerName;

		public static class PersonBuilder {
			private String fName;
			private String lName;
			private short age;
			private String employerName;

			public PersonBuilder(String fName, String lName) {
				this.fName = fName;
				this.lName = lName;
			}

			public PersonBuilder age(short age) {
				this.age = age;
				return this;
			}

			// The builder's setter methods return the builder itself so that
			// invocations can be chained.
			public PersonBuilder employerName(String employerName) {
				this.employerName = employerName;
				return this;
			}

			public Person build() {
				return new Person(this);
			}
		}

		Person(PersonBuilder p) {
			this.fName = p.fName;
			this.lName = p.lName;
			this.age = p.age;
			this.employerName = p.employerName;

		}

		@Override
		public String toString() {
			StringBuilder temp = new StringBuilder("Peron details: ");
			temp.append(this.fName).append(" ").append(this.lName).append(" of age ").append(this.age);

			return temp.toString();
		}

	}

	public static void main(String[] args) {

		Person p = new Person.PersonBuilder("John", "Jacob").age((short) 45).employerName("Apple").build();

		System.out.println(p);
	}
}

Disadvantage of Builder pattern.

In order to create an object, you must first create its builder. It could be a problem in some performance critical situations.

When to use Builder design pattern?

the Builder pattern is preferred for classes whose constructors or static factories would have more parameters (four or more), especially if most of those parameters are optional.

In Java singleton, how do you prevent creating instance using reflection?

Create a constructor and throw InstantiationError when the private singleton instance reference is not null.

private Singleton() {
    if( Singleton.singleton != null ) {
        throw new InstantiationError( "Creating of this object is not allowed." );
    }
}

How do we ensure Singleton Design Pattern in a clustered Environment?

Each JVM will have its own copy of singleton object in clustered environment, so we may have to use different techniques to ensure only one instance exists across multiple JVMs in clustered environment.

Terracotta, Oracle Coherence provides an in memory replication of objects across JVMs that enables singleton view.

Cluster-aware cache providers like Swarm Cache or JBoss TreeCache create cache entries as singletons.

JBoss and Weblogic has the concept of Singleton Service where only instance runs within the cluster and all clients will look up to the same instance. WebSphere application server also supports the concept of singleton across clusters.

JMS, JGroups software allows to form a group and Applications (JVMs) can participate and JGroups will send messages to everyone in the group so that they can be in sync.

Difference between Singleton Pattern and static Class in Java.

Singleton pattern gives you an Object, while later just provide static methods.

Static class provides better performance than Singleton pattern, because static methods are bonded on compile time.

Static methods cannot be overridden while we can override methods defined in a Singleton class by extending it.

Singleton classes can be lazy loaded, but static class does not have such advantages and always eagerly loaded.

If you need to maintain state than Singleton pattern is better choice than static class as it requires additional synchronization mechanism.

With Singleton, you can use Inheritance and Polymorphism to extend a base class, implement an interface and capable of providing different implementations.

singleton can be serialized to preserve its state.

Give example of singleton class from JDK.

java.lang.Runtime is a Singleton class in Java.

When to use Static Class in place of Singleton in Java?

If your Singleton is not maintaining any state, and just provide global access to methods, then consider using static class, as static methods are faster than Singleton, because of static binding during compile time.

Explain Bridge design pattern in Java.

Bridge design pattern is a structural design pattern.

It states that "Decouple the abstraction from its implementation so that both can vary independently".

The example code is available here.

Explain prototype pattern in Java.

Prototype pattern is one of the creation design patterns in Java which states that "Create objects based on a template of an existing object through cloning".

Explain Template method design Pattern in Java.

Template pattern outlines an algorithm in template method and let subclass implement individual steps.

Template method is final, so that subclass cannot override and change the steps, however individual steps are declared abstract, so that child classes can implement them.

What is filter pattern in Java?

Filter pattern also known as Criteria pattern, enables developers to filter a set of objects using different criteria and chaining them in a decoupled fashion through logical operations. This is a structural pattern as it combines multiple criteria to obtain single criteria.

Explain Proxy design pattern in Java.

Proxy design pattern, a structural pattern, states "that Allows for object level access control by acting as a pass through entity or a placeholder object. "

This pattern is recommended when,

  • Objects need to be created on demand.
  • Access control for the original object is required,
  • Added functionality is required when an object is accessed.
What is Adapter pattern in Java?

Adapter design pattern is one of the structural design patterns and it allows two unrelated interfaces to work together. The object that joins these unrelated interface is called an Adapter.

Difference between the Bridge and Adapter pattern in Java.

The Adapter pattern is more about getting your existing code to work with a newer system or interface.

The Bridge pattern allows you to possibly have alternative implementations of an algorithm or system.

Adapter makes things work after they're designed; Bridge makes them work before they are.

What is Chain of Responsibility Pattern in Java?

The Chain of Responsibility is a behavioral pattern, which states that "Give more than one object an opportunity to handle a request by linking receiving objects together. "

In JavaEE, the Servlet filters implement the Chain of Responsibility pattern, and may also decorate the request to add extra information before the request is handled by a servlet.

Explain Intercepting Filter pattern in Java.

Intercepting Filters trigger actions before or after an incoming request is processed by a handler.

Intercepting filters represents centralized components in a web application, common to all requests and extensible without affecting existing handlers.

AOP is based on Interception filter pattern.

Disadvantage of using factory pattern for object creation.

We need to do subclassing just to instantiate a particular class.

Which pattern provides greater abstraction than factory pattern?

Abstract factory provides better abstraction as it encapsulates a group of individual factories.

Disadvantages of the singleton pattern.

Singleton violates single responsibility principle.

Singleton classes cannot be subclassed.

They inherently cause code to be tightly coupled.

Which classes are candidates of Singleton?

Any class that needs to be available to the entire application and only one instance should exist is the ideal candidate for becoming Singleton. One example of this is Runtime class that ensures only one Runtime environment available under JVM.

What is double checked locking in Singleton?

Double-checked locking prevents creating a duplicate instance of Singleton when call to getInstance() method is made in a multi-threading environment. In Double checked locking pattern as shown in below example, singleton instance is checked two times before initialization.

public class Singleton{
private static Singleton _INSTANCE;

public static Singleton getInstance()
{
	if(_INSTANCE==null) {
		synchronized(Singleton.class){
// double checked locking inside synchronized block
			if(_INSTANCE==null){_INSTANCE=new Singleton();}
			}
		}
	return _INSTANCE;
	}
}

How to prevent creating another instance of Singleton using clone() method?

Do not implement the Cloneable interface at Singleton class and however if it implemented, override the clone method and throw an exception to prevent cloning.

How to prevent creating another instance of Singleton during serialization?

You can prevent by using readResolve() method since during serialization readObject() is used to create an instance and it returns new instance every time. However, by using readResolve you can replace it with original Singleton instance.

Explain mediator pattern in Java.

Mediator design pattern is one of the behavioral design patterns and it is used to provide a centralized communication medium between different objects in a system.

Its intent is to "Allows loose coupling by encapsulating the way disparate sets of objects interact and communicate with each other. Allows for the actions of each object set to vary independently of one another".

Give few examples of Mediator Pattern in JDK.
  • java.util.Timer class schedule...() method,
  • Java Concurrency Executor execute() method.
  • java.lang.reflect.Method invoke() method.

Explain Command design pattern in Java.

Command Pattern is one of the Behavioral Design Patterns and it is used to implement loose coupling in a request-response model.

java.lang.Runnable interface and Swing Action (javax.swing.Action) implements command design pattern.

What is State Design Pattern in Java?

State design pattern is one of the behavioral design patterns and it is used when an Object change its behavior based on its internal state.

When cloning an object is preferred over creating a new object in Java?

If the cost of creating an object is larger and time consuming than the cost of cloning the object, then it is preferred to clone the object.

Name some of the design patterns that makes use of singleton pattern.

The Abstract Factory, Builder, and Prototype patterns may use singleton pattern. Also fa├žade objects are often created using singleton pattern.

Explain Memento pattern in Java.

The Memento pattern is known as behavioural pattern and it "Captures and externalizes an object's internal state so that it can be restored later, all without violating encapsulation" .

When do you use memento design pattern ?

The Memento pattern provides undo mechanism in your application when the internal state of an object need to be restored at a later stage. Using serialization along with this pattern, it's easy to preserve the object state and restore it later.

Explain visitor pattern in Java.

Visitor pattern is one of the behavioural patterns and it's definition is as follows, "allows for one or more operation to be applied to a set of objects at runtime, decoupling the operations from the object structure".

What is value object design pattern?

The value object pattern is an object that encapsulates a set of values that is moved across the boundary so that attempts to get the values of those attributes are local that eliminates redundant network calls. This pattern provides the best way to exchange data across tiers or system boundaries, especially when there is network communication involved. This is a pattern that solves performance issues around network latency.

What is Transfer object design pattern in Java?

Transfer object is a simple Java class with fields and contains no business logic. They are serializable POJO classes and have accessor methods (getter and setters) to access fields. These classes pass data between layers, they need not match business objects. Usually, Transfer objects group arguments to service method call.

Explain Service Locator design pattern in Java.

Service Locator pattern is one of the core J2EE Design patterns.

Service Locator object abstracts JNDI usage and hides the complexities of initial context creation, EJB home object lookup, and EJB object re-creation. Multiple clients can reuse the Service Locator object to reduce code complexity, provide a single point of control, and improve performance by providing a caching facility.

Mention some of the core J2EE design patterns.

At the Presentation layer, the most used design patterns are Intercepting filter, Front Controller, View Helper, Dispatcher View, Composite View, Application Controller and Context object.

At the Business Layer, the design patterns are Business Delegate, Session Facade, Transfer Object, Business Object, Value List Handler, Service Locator, Application Service and Transfer Object Assembler.

At the Integration Layer, the design patterns are DAO, Service Activator, Web service broker and Domain store.

Difference between Front Controller and View Helper in J2EE.

Front Controller is a controller pattern which provides a centralized controller for managing requests. All incoming requests are delegated to front controller first and it is useful when your application has multiple entry points which you want to centralize through a single point for standardized processing.

View Helper, on the other hand, is in the view layer. It simply arranges view components for the user and delegates processing to other business components so the view component doesn't have to contain any processing logic other than logic to present views.Example is if you need a menu selection to persist through all the views, you store the menu items on the View Helper which calls different views but you will always have access to the menu.

Usually both Front controller and view helper are used together.

Advantages of Factory method design pattern.

Factory Method Pattern allows the sub-classes to choose the type of objects to create.

Promotes the loose-coupling by eliminating the need to bind application-specific classes into the code. That means the code interacts solely with the resultant interface or abstract class, so that it will work with any classes that implement that interface or that extends that abstract class.

What is a monolithic architecture?

A monolithic architecture describes a single-tiered software application in which the user interface and data access code are combined into a single program from a single platform. For example, Java war file wraps UI component as well as controller and Business logic.

Is template method pattern an example of Inversion of control?

Yes. As per wiki,the template method is used in frameworks, where each implements the invariant parts of a domain's architecture, leaving "placeholders" for customisation options. This is an example for inversion of control, also called the Hollywood principle.

Give an example of Template method pattern from JDK.

java.util.Collections.sort method implements template method pattern.

Disadvantages of Immutable class.

Additional overhead at garbage collection.

Constructor injection is complex which affects reflection based frameworks.

Types of messaging patterns.
  • Channel pattens,
  • Routing patterns,
  • Message construction patterns,
  • Transformation and endpoint patterns.
«
»
Generics

Comments & Discussions