Skip to main content

Java Design Patterns Interview Questions part - 2



Java Design Patterns



1.What are the examples of Interpreter design pattern in JDK?
                         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:
java.util.Patternjava.text.NormalizerSubclasses of java.text.Format: DateFormat,MessageFormat, NumberFormatSubclasses of javax.el.ELResolver: ArrayELResolver,MapELResolver, CompositeELResolver etc.

2. What are the examples of Mediator design pattern in JDK?
                          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:
java.util.Timer: schedule() methods in Timer class act as Mediator between the clients and the TimerTask to be scheduled. 
java.util.concurrent.Executor.execute(): The execute() method in an Executor class acts as a Mediator to execute the different tasks 
.java.util.concurrent.ExecutorService  java.lang.reflect.Method.invoke(): In Method class of reflection package, invoke() method acts as a Mediator. 
 java.util.concurrent.ScheduledExecutorService: Here also schedule() method and its variants are Mediator pattern implementations.
3. What are the examples of Strategy design pattern in JDK? 
                  In JDK there are many places where Strategy design pattern is used.
       Some of these are as follows:

1. java.util.Comparator: In a Comparator we can use compare() method to change the strategy used by Collections.sort() method. 
2. javax.servlet.http.HttpServlet: In a HttpServlet class service() and doGet(), doPost() etc. methods take HttpServletRequest and HttpServletResponse and the implementor of Servlet processes it based on the strategy it selects.

4. What are the examples of Visitor design pattern in JDK?
                        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:
javax.lang.model.element.AnnotationValue
and
AnnotationValueVisitor
java.nio.file.FileVisitor and SimpleFileVisitor
javax.lang.model.type.TypeMirror and TypeVisitor
javax.lang.model.element.Element and ElementVisitor
javax.faces.component.visit.VisitContext
and
VisitCallback

5. How Decorator design pattern is different from Proxy pattern? 
                  Main differences between Decorator and Proxy design pattern are:
           Decorator provides an enhanced interface after decorating it with additional features. Proxy provides same interface since it is just acting as a proxy to another object. Decorator is a type of Composite pattern with only one component. But each decorator can add additional features. Since it is one component in Decorator, there is no object aggregation. Proxy can also provide performance improvement by lazy loading. There is nothing like this available in Decorator. Decorator follows recursive composition. Proxy is just one object to another object access. Decorator is mostly used for building a variety of objects. Proxy is mainly used for access to another object.

6. What are the different scenarios to use Setter and Constructor based injection in Dependency Injection (DI) design pattern?
                      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.

7. What are the different scenarios for using Proxy design pattern? 
                Proxy design pattern can be used in a wide variety of scenario in Java. Some of these are as follows:
1. Virtual Proxy: This is a virtual object that acts as a proxy for objects that are very expensive to create. It is used in Lazy Loading. When client makes the first request, the real object is created. 
2. Remote Proxy: This is a local object that provides access to a remote object. It is generally used in Remote Method Invocation (RMI) and Remote Procedure Call (RPC). It is also known as a Stub. 
3. Protective Proxy: This is an object that control the access to a Master object. It can authenticate and authorize the client for accessing the Master object. If client has right permissions, it allows client to access the main object. 
4. Smart Proxy: It is an object that can add additional information to the main object. It can track the number of other objects accessing the main object. It can track the different clients from where request is coming. It can even deny access to an object if the number of requests is greater than a threshold.


8. What is the main difference between Adapter and Proxy design pattern?
                    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.






9. When will you use Adapter design pattern in Java?
                    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.

10. What are the examples of Adapter design pattern in JDK?
                     In JDK there are many places where Adapter design pattern is used.
              Some of these are as follows:


java.util.Arrays.asList(): This method can adapt an Array to work as a List.java.util.Collections.list(): This method can adapt any collection to provide List behavior.java.util.Collections.enumeration(): This method returns an enumeration over the collection.java.io.InputStreamReader(InputStream): This method adapts a Stream to Reader class.java.io.OutputStreamWriter(OutputStream): This method adapts an OutputStream to Writer class.javax.xml.bind.annotation.adapters.XmlAdapter.marshal()

11. What is the benefit we get by using static factory method to create object?
                  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().


12. What are the examples of Builder design pattern in JDK? 
               In JDK there are many places where Builder design pattern is used. Some of these are as follows:
  1. java.lang.StringBuilder.append(): StringBuilder is based on Builder pattern.
  2. java.nio.IntBuffer.put(): Invocation of put() method return IntBuffer. Also there are many variants of this method to build the IntBuffer.
  3. javax.swing.GroupLayout.Group.addComponent(): We can use addComponent() method to build a UI that can contain multiple levels of components.
  4. java.lang.Appendable
  5. java.lang.StringBuffer.append(): StringBuffer is similar to StringBuilder and it is also based on Builder design pattern.


13. What are the examples of Abstract Factory design pattern in JDK?
            In JDK there are many places where Abstract Factory design pattern is used. Some of these are as follows:
javax.xml.xpath.XPathFactory.newInstance()javax.xml.parsers.DocumentBuilderFactory.newInstance()javax.xml.transform.TransformerFactory.newInstance()

14. What are the examples of Decorator design pattern in JDK?

               In JDK there are many places where Decorator design pattern is used. Some of these are as follows:
1. In java.io package many classes use Decorator pattern. Subclasses of java.io.InputStream, OutputStream, Reader and Writer have a constructor that can take the instance of same type and decorate it with additional behavior.2. In java.util.Collections, there are methods like checkedCollection(), checkedList(), checkedMap(),synchronizedList(), synchronizedMap(), synchronizedSet(), unmodifiableSet(), unmodifiableMap() and unmodifiableList() methods that can decorate an object and return the same type.3. In javax.servlet package, there are classes like javax.servlet.http.HttpServletRequestWrapper and HttpServletResponseWrapper that are based on Decorator design pattern.


15. What are the examples of Proxy design pattern in JDK?

               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:

java.lang.reflect.Proxyjava.rmi.*javax.inject.Injectjavax.ejb.EJBjavax.persistence.PersistenceContext
16. What are the examples of Chain of Responsibility design pattern in JDK?
                In JDK there are many places where Chain of Responsibility design pattern is used. Some of these are as follows:
1. java.util.logging.Logger.log(): In this case Logger class provides multiple variations of log() method that can take the responsibility of logging from client in different scenarios. The client has to just call the appropriate log() method and Logger will take care of these commands. 
2. javax.servlet.Filter.doFilter(): In the Filter class, the Container calls the doFilter method when a request/response pair is passed through the chain. With filter the request reaches to the appropriate resource at the end of the chain. We can pass FilterChain in doFilter() method to allow the Filter to pass on the request and response to the next level in the chain.
17. What are the main uses of Command design pattern? 
                 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:
1. Graphic User Interface (GUI): In GUI and menu items, we use command pattern. By clicking a button we can read the current information of GUI and take an action. 
2. Macro Recording: If each of user action is implemented as a separate Command, we can record all the user actions in a Macro as a series of Commands. We can use this series to implement the “Playback” feature. In this way, Macro can keep on doing same set of actions with each replay. 
3. Multi-step Undo: When each step is recorded as a Command, we can use it to implement Undo feature in which each step can by undo. It is used in text editors like MS-Word. 
4. Networking: We can also send a complete Command over the network to a remote machine where all the actions encapsulated within a Command are executed. 
5. Progress Bar: We can implement an installation routine as a series of Commands. Each Command provides the estimate time. When we execute the installation routine, with each command we can display the progress bar.  
6. Wizard: In a wizard flow we can implement steps as Commands. Each step may have complex task that is just implemented within one command. 
7. Transactions: In a transactional behavior code there are multiple tasks/updates. When all the tasks are done then only transaction is committed. Else we have to rollback the transaction. In such a scenario each step is implemented as separate Command.

18. What are the examples of Command design pattern in JDK?
               In JDK there are many places where Command design pattern is used. Some of these are as follows:
All implementations of java.lang.RunnableAll implementations of javax.swing.Action

19.What is the use of Interceptor design pattern?
                       Interceptor design pattern is used for intercepting a request. Primary use of this pattern is in Security policy implementation. We can use this pattern to intercept the requests by a client to a resource. At the interception we can check for authentication and authorization of client for the resource being accessed. In Java it is used in javax.servlet.Filter interface. This pattern is also used in Spring framework in HandlerInterceptor and MVC interceptor.

20.What are the Architectural patterns that you have used?
                     Architectural patterns are used to define the architecture of a Software system. Some of the patterns are as follows:
1. MVC: Model View Controller. This pattern is extensively used in the architecture of Spring framework. 
2. Publish-subscribe: This pattern is the basis of messaging architecture. In this case messages are published to a Topic. And subscribers subscribe to the topic of their interests. Once the message is published to a topic in which a Subscriber has an interest, the message is consumed by the relevant subscriber 
.3. Service Locator: This design pattern is used in a service like JNDI to locate the available services. It uses as central registry to maintain the list of services.  
4. n-Tier: This is a generic design pattern to divide the architecture in multiple tiers. E.g. there is 3-tier architecture with Presentation layer, Application layer and Data access layer. It is also called multi-layer design pattern. 
5. Data Access Object (DAO): This pattern is used in providing access to database objects. The underlying principle is that we can change the underlying database system, without changing the business logic. Since business logic talks to DAO object, there is no impact of changing Database system on business logic. 

6. Inversion of Control (IoC): This is the core of Dependency Injection in Spring framework. We use this design pattern to increase the modularity of an application. We keep the objects loosely coupled with Dependency Injection.


21. What are the popular uses of Façade design pattern?                Some of the popular uses of Façade design pattern are as follows:
1. A Façade provides convenient methods for common tasks that are used more often. 
2. A Façade can make the software library more readable. 
3. A Façade can reduce the external dependencies on the working of inner code. 
4. A Façade can act as a single well-designed API by wrapping a collection of poorly designed APIs. 
5. A Façade pattern can be used when a System is very complex and difficult to use. It can simplify the usage of complex system.
22.What is the difference between Builder design pattern and Factory design pattern?             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.


23.What is Memento design pattern?                 Memento design pattern is used to implement rollback feature in an object. In a Memento pattern there are three objects:
Originator: This is the object that has an internal state. 
Caretaker: This is the object that can change the state of Originator. But it wants to have control over rolling back the change. 
Memento: This is the object that Caretaker gets from Originator, before making and change. If Caretaker wants to Rollback the change it gives Memento back to Originator. Originator can use Memento to restore its own state to the original state.
                  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.

24.What is an AntiPattern?                   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:

1. Gold Plating: Keep on adding extra things on a working solution even though these extra things do not add any additional value. 
2. Spaghetti Code: Program that are written in a very complex way and are hard to understand due to misuse of data structures. 
3. Coding By Exception: Adding new code just to handle exception cases and corner case scenarios. 
4. Copy Paste Programming: Just copying the same code multiple times rather than writing generic code that can be parameterized.


25.What is a Data Access Object (DAO) design pattern?                  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.


26. How can we implement Producer Consumer design pattern in Java?

              We can use BlockingQueue in Java to implement Producer Consumer design pattern. It is a concurrent design pattern.


Basic Java       OOPs        Static       Inheritance  

Comments

Popular posts from this blog

DOCKER Interview questions

DOCKER 1. What is Docker? Docker is Open Source software. It provides the automation of Linux application deployment in a software container. We can do operating system level virtualization on Linux with Docker. Docker can package software in a complete file system that contains software code, runtime environment, system tools, & libraries that are required to install and run the software on a server. 2. What is the difference between Docker image and Docker container? Docker container is simply an instance of Docker image. A Docker image is an immutable file, which is a snapshot of container. We create an image with build command. When we use run command, an Image will produce a container. In programming language, an Image is a Class and a Container is an instance of the class. 3. How will you remove an image from Docker? We can use docker rmi command to delete an image from our local system. Exact command is: % docker rmi <Image Id> If we want to fin

Microservices Interview Questions

Microservices Interview Questions 1. What is a Microservice in Java? A Microservice is a small and autonomous piece of code that does one thing very well. It is focused on doing well one specific task in a big system. It is also an autonomous entity that can be designed, developed and deployed independently. Generally, it is implemented as a REST service on HTTP protocol, with technology-agnostic APIs. Ideally, it does not share database with any other service. 2. What are the benefits of Microservices architecture? Microservices provide many benefits. Some of the key benefits are: 1.      Scaling : Since there are multiple Microservices instead of one monolith, it is easier to scale up the service that is being used more. Eg. Let say, you have a Product Lookup service and Product Buy service. The frequency of Product Lookup is much higher than Product Buy service. In this case, you can just scale up the Product Lookup service to run on powerful hardware with multipl

Cloud Computing Interview Questions

Cloud Computing 1. What are the benefits of Cloud Computing? There are ten main benefits of Cloud Computing: Flexibility : The businesses that have fluctuating bandwidth demands need the flexibility of Cloud Computing. If you need high bandwidth, you can scale up your cloud capacity. When you do not need high bandwidth, you can just scale down. There is no need to be tied into an inflexible fixed capacity infrastructure. Disaster Recovery : Cloud Computing provides robust backup and recovery solutions that are hosted in cloud. Due to this there is no need to spend extra resources on homegrown disaster recovery. It also saves time in setting up disaster recovery. Automatic Software Updates : Most of the Cloud providers give automatic software updates. This reduces the extra task of installing new software version and always catching up with the latest software installs. Low Capital Expenditure : In Cloud computing the model is Pay as you Go. This means there is very