Java / Design Patterns
1. 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.
2. 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 ...
3. 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.
4. 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 close...
5. Difference between Strategy and State design Pattern in Java.
State design pattern is used to define and manage the state of the object, while Strategy pattern is used to define a set of interchangeable algorithms and let's client choose one of them. So Strategy pattern is a client-driven pattern while Object can manage their state itself.
6. 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.
7. 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...
8. 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.
9. 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.
10. 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.
11. 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 Pr...
12. 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.
13. 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 interfac...
14. 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. A...
15. 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...
16. 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.
17. 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 Me...
18. 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.
19. 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.
20. Types of Java Design patterns.
Java Design Patterns are divided into three categories: creational, structural and behavioral design patterns.
21. Name few Creational Patterns in Java.
Abstract Factory, Builder, Factory method, prototype and singleton are some of the creational design patterns.
22. Name some of the structural design patterns in Java.
Adapter, Bridge, Composite, Decorator,Flyweight, Facade and proxy are some of the structural design patterns.
23. 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.
24. 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 ...
25. 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 me...
26. 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 dire...
27. 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 , wh...
28. 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 a default value fo...
29. 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" )...
30. 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.
31. 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 set...
32. 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.
33. 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.
34. 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." ); } }
35. 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 ena...
36. 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 ext...
37. Give example of singleton class from JDK.
java.lang.Runtime is a Singleton class in Java.
38. 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.
39. 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.
40. 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".
41. 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.
42. 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.
43. 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 functiona...
44. 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 .
45. 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.
46. 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 ex...
47. 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.
48. Disadvantage of using factory pattern for object creation.
We need to do subclassing just to instantiate a particular class.
49. Which pattern provides greater abstraction than factory pattern?
Abstract factory provides better abstraction as it encapsulates a group of individual factories.
50. Disadvantages of the singleton pattern.
Singleton violates single responsibility principle . Singleton classes cannot be subclassed . They inherently cause code to be tightly coupled .
51. 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.
52. 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...
53. 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.
54. 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.
55. 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....
56. 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.
57. 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.
58. 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 .
59. 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.
60. 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.
61. 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 " .
62. 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.
63. 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 ".
64. 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...
65. 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 argu...
66. 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,...
67. 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, Busine...
68. 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 standardiz...
69. 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 ...
70. 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.
71. 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.
72. Give an example of Template method pattern from JDK.
java.util.Collections.sort method implements template method pattern.
73. Disadvantages of Immutable class.
Additional overhead at garbage collection. Constructor injection is complex which affects reflection based frameworks.
74. Types of messaging patterns.
Channel pattens, Routing patterns, Message construction patterns, Transformation and endpoint patterns.
75. Difference between filter and interceptor patterns in Spring MVC.
A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. Filters typically do not themselves create responses, but instead provide universal functions that can be "attached" to any type of servlet or JSP page. Interceptors ...