1. Singleton pattern
2. What is Service Locator pattern?
Ans:The Service Locator pattern locates J2EE (Java 2 Platform, Enterprise Edition) services for clients and thus abstracts the complexity of network operation and J2EE service lookup as EJB (Enterprise JavaBean) Interview Questions - Home and JMS (Java Message Service) component factories. The Service Locator hides the lookup process's implementation details and complexity from clients. To improve application performance, Service Locator caches service objects to eliminate unnecessary JNDI (Java Naming and Directory Interface) activity that occurs in a lookup operation.
3. What is Session Facade pattern?
Ans: Session facade is one design pattern that is often used while developing enterprise applications. It is implemented as a higher level component (i.e.: Session EJB), and it contains all the iteractions between low level components (i.e.: Entity EJB). It then provides a single interface for the functionality of an application or part of it, and it decouples lower level components simplifying the design. Think of a bank situation, where you have someone that would like to transfer money from one account to another. In this type of scenario, the client has to check that the user is authorized, get the status of the two accounts, check that there are enough money on the first one, and then call the transfer. The entire transfer has to be done in a single transaction otherwise is something goes south, the situation has to be restored.
As you can see, multiple server-side objects need to be accessed and possibly modified. Multiple fine-grained invocations of Entity (or even Session) Beans add the overhead of network calls, even multiple transaction. In other words, the risk is to have a solution that has a high network overhead, high coupling, poor reusability and mantainability.
The best solution is then to wrap all the calls inside a Session Bean, so the clients will have a single point to access (that is the session bean) that will take care of handling all the rest.
4. What is Data Access Object pattern?
Ans:The Data Access Object (or DAO) pattern: separates a data resource's client interface from its data access mechanisms adapts a specific data resource's access API to a generic client interface
The DAO pattern allows data access mechanisms to change independently of the code that uses the data.
The DAO implements the access mechanism required to work with the data source. The data source could be a persistent store like an RDBMS, an external service like a B2B exchange, a repository like an LDAP database, or a business service accessed via CORBA Internet Inter-ORB Protocol (IIOP) or low-level sockets. The business component that relies on the DAO uses the simpler interface exposed by the DAO for its clients. The DAO completely hides the data source implementation details from its clients. Because the interface exposed by the DAO to clients does not change when the underlying data source implementation changes, this pattern allows the DAO to adapt to different storage schemes without affecting its clients or business components. Essentially, the DAO acts as an adapter between the component and the data source.
5. What design patterns are used in Struts?
Ans:Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern. Struts also implement the following J2EE design patterns.
Service to Worker
Dispatcher View
Composite View (Struts Tiles)
Front Controller
View Helper
Synchronizer Token
6. Comparing Adapter Pattern with other Patterns:
Ans:
1. Adapter converts one interface to another, Decorator doesn't alter interface but adds responsibility. Facade makes an interface simpler.
Decorator is thus more transparent to the application than an adapter is. As a consequence, Decorator supports recursive composition, which isn't possible with pure Adapters.
2. Adapters allows client to make use of libraries and subsets without changing any code. Decorators allow new behaviour to be added to the classes with out altering the existing code.
3. Adapter make things work after they're designed, Bridge makes them work before they are.
4. Bridge is designed up-front to let the abstraction and the implementation vary independently. Adapter is retrofitted to make unrelated classes work together.
5. Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface.
6. Facade defines a new interface, whereas Adapter reuses an old interface. Remember that Adapter makes two existing interfaces work together as opposed to defining an entirely new one.
7. Which are the three main categories of design patterns?
Ans:
There are three basic classifications of patterns Creational, Structural, and Behavioral patterns.
Creational Patterns
• Abstract Factory:- Creates an instance of several families of classes
• Builder: - Separates object construction from its representation
• Factory Method:- Creates an instance of several derived classes
• Prototype:- A fully initialized instance to be copied or cloned
• Singleton:- A class in which only a single instance can exist
Note: - The best way to remember Creational pattern is by ABFPS (Abraham Became First President of States).
Structural Patterns
• Adapter:-Match interfaces of different classes.
• Bridge:-Separates an object’s abstraction from its implementation.
• Composite:-A tree structure of simple and composite objects.
• Decorator:-Add responsibilities to objects dynamically.
• Façade:-A single class that represents an entire subsystem.
• Flyweight:-A fine-grained instance used for efficient sharing.
• Proxy:-An object representing another object.
Note : To remember structural pattern best is (ABCDFFP)
Behavioral Patterns
• Mediator:-Defines simplified communication between classes.
• Memento:-Capture and restore an object's internal state.
• Interpreter:- A way to include language elements in a program.
• Iterator:-Sequentially access the elements of a collection.
• Chain of Resp: - A way of passing a request between a chain of objects.
• Command:-Encapsulate a command request as an object.
• State:-Alter an object's behavior when its state changes.
• Strategy:-Encapsulates an algorithm inside a class.
• Observer: - A way of notifying change to a number of classes.
• Template Method:-Defer the exact steps of an algorithm to a subclass.
• Visitor:-Defines a new operation to a class without change.
Note: - Just remember Music....... 2 MICS On TV (MMIICCSSOTV).
8. How can I make sure at most one instance of my class is ever created?
Ans:This is an instance where the Singleton design pattern would be used. You need to make the constructor private (so nobody can create an instance) and provide a static method to get the sole instance, where the first time the instance is retrieved it is created:
public class Mine {
private static Mine singleton;
private Mine() {
}
public static synchronized Mine getInstance() {
if (singleton == null) {
singleton = new Mine();
}
return singleton;
}
// other stuff...
}
9. What major patterns do the Java APIs utilize? Design patterns are used and supported extensively throughout the Java APIs. Here are some examples:
10. Can you explain singleton pattern?
11. J2EE design patterns
Ans:
a)Presentation-tier patterns:
What is Intercepting Filter pattern?
Ans. Provides a solution for pre-processing and post-processing a request. It allows us to declaratively apply filters for intercepting requests and responses. For ex. Servlet filters.
What is Front Controller pattern?
Ans. It manages and handles requests through a centralized code. This could either be through a servlet or a JSP (through a Java Bean). This Controller takes over the common processing which happens on the presentation tier. The front controller manages content retrieval, security, view management and retrieval.
What is View Helper pattern?
Ans. There generally are two parts to any application – the presentation and the business logics. The “View” is responsible for the output-view formatting whereas “Helper” component is responsible for the business logic. Helper components do content retrieval, validation and adaptation. Helper components generally use Business delegate pattern to access business classes.
What is Composite View pattern?
Ans. This pattern is used for creating aggregate presentations (views) from atomic sub-components. This architecture enables says piecing together of elementary view components which makes the presentation flexible by allowing personalization and customization.
What is Service to Worker pattern?
Ans. This is used in larger applications wherein one class is used to process the requests while the other is used to process the view part. This differentiation is done for maintainability.
What is Dispatcher View pattern?
Ans. This is similar to Service to Worker pattern except that it is used for smaller applications. In this one class is used for both request and view processing.
What is Business Delegate pattern?
Ans. This pattern is used to reduce the coupling between the presentation and business-logic tier. It provides a proxy to the façade from where one could call the business classes or DAO class. This pattern can be used with Service Locator pattern for improving performance.
What is Value Object (VO) pattern?
Ans. Value Object is a serializable object which would contain lot of atomic values. These are normal java classes which may have different constructors (to fill in the value of different data) and getter methods to get access to these data. VOs are used as a course grained call which gets lots of data in one go (this reduces remote overhead). The VO is made serializable for it to be transferred between different tiers within a single remote method invocation.
b)Business tier patterns for business logic (EJB) tier
Business delegate, Value Object, Session Façade, Composite Entity, Value Object Assembler, Value List Handler, and Service Locator.
What is Session Façade pattern?
Ans. This pattern hides the complexity of business components and centralizes the workflow. It provides course-grained interfaces to the clients which reduces the remote method overhead. This pattern fits well with declarative transactions and security management.
What is Value Object Assembler pattern?
Ans. This pattern allows for composing a Value Object from different sources which could be EJBs, DAOs or Java objects.
What is Value List Handler pattern?
Ans. This pattern provides a sound solution for query execution and results processing.
What is Service Locator pattern?
Ans. It provides a solution for looking-up, creating and locating services and encapsulating their complexity. It provides a single point of control and it also improves performance.
What is Data Access Object pattern?
Ans. It provides a flexible and transparent access to the data, abstracts the data sources and hides the complexity of Data persistence layer. This pattern provides for loose coupling between business and data persistence layer.
What is EJB Command pattern?
Ans. Session Façade and EJB Command patterns are competitor patterns. It wraps business logic in command beans, decouples the client and business logic tier, and reduces the number of remote method invocations.
What is Version Number pattern?
Ans. This pattern is used for transaction and persistence and provides a solution for maintaining consistency and protects against concurrency. Every time a data is fetched from the database, it comes out with a version number which is saved in the database. Once any update is requested on the same row of the database, this version is checked. If the version is same, the update is allowed else not.
12. What all patterns are used to improve performance and scalability of the application?
Ans. VO, Session Façade, Business Delegate and Service Locator.
13. What design patterns could be used to manage security?
Ans. Single Access Point, Check point and Role patterns.
14. What design patterns do you use. Describe one you have used (not singleton)? (Hint: e.g. Builder, Factory, Visitor, Chain of Command )
15. Describe the observer pattern and an example of how it would be used? (Hint: e.g. event notification when model changes to view )
2. What is Service Locator pattern?
Ans:The Service Locator pattern locates J2EE (Java 2 Platform, Enterprise Edition) services for clients and thus abstracts the complexity of network operation and J2EE service lookup as EJB (Enterprise JavaBean) Interview Questions - Home and JMS (Java Message Service) component factories. The Service Locator hides the lookup process's implementation details and complexity from clients. To improve application performance, Service Locator caches service objects to eliminate unnecessary JNDI (Java Naming and Directory Interface) activity that occurs in a lookup operation.
3. What is Session Facade pattern?
Ans: Session facade is one design pattern that is often used while developing enterprise applications. It is implemented as a higher level component (i.e.: Session EJB), and it contains all the iteractions between low level components (i.e.: Entity EJB). It then provides a single interface for the functionality of an application or part of it, and it decouples lower level components simplifying the design. Think of a bank situation, where you have someone that would like to transfer money from one account to another. In this type of scenario, the client has to check that the user is authorized, get the status of the two accounts, check that there are enough money on the first one, and then call the transfer. The entire transfer has to be done in a single transaction otherwise is something goes south, the situation has to be restored.
As you can see, multiple server-side objects need to be accessed and possibly modified. Multiple fine-grained invocations of Entity (or even Session) Beans add the overhead of network calls, even multiple transaction. In other words, the risk is to have a solution that has a high network overhead, high coupling, poor reusability and mantainability.
The best solution is then to wrap all the calls inside a Session Bean, so the clients will have a single point to access (that is the session bean) that will take care of handling all the rest.
4. What is Data Access Object pattern?
Ans:The Data Access Object (or DAO) pattern: separates a data resource's client interface from its data access mechanisms adapts a specific data resource's access API to a generic client interface
The DAO pattern allows data access mechanisms to change independently of the code that uses the data.
The DAO implements the access mechanism required to work with the data source. The data source could be a persistent store like an RDBMS, an external service like a B2B exchange, a repository like an LDAP database, or a business service accessed via CORBA Internet Inter-ORB Protocol (IIOP) or low-level sockets. The business component that relies on the DAO uses the simpler interface exposed by the DAO for its clients. The DAO completely hides the data source implementation details from its clients. Because the interface exposed by the DAO to clients does not change when the underlying data source implementation changes, this pattern allows the DAO to adapt to different storage schemes without affecting its clients or business components. Essentially, the DAO acts as an adapter between the component and the data source.
5. What design patterns are used in Struts?
Ans:Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern. Struts also implement the following J2EE design patterns.
Service to Worker
Dispatcher View
Composite View (Struts Tiles)
Front Controller
View Helper
Synchronizer Token
6. Comparing Adapter Pattern with other Patterns:
Ans:
1. Adapter converts one interface to another, Decorator doesn't alter interface but adds responsibility. Facade makes an interface simpler.
Decorator is thus more transparent to the application than an adapter is. As a consequence, Decorator supports recursive composition, which isn't possible with pure Adapters.
2. Adapters allows client to make use of libraries and subsets without changing any code. Decorators allow new behaviour to be added to the classes with out altering the existing code.
3. Adapter make things work after they're designed, Bridge makes them work before they are.
4. Bridge is designed up-front to let the abstraction and the implementation vary independently. Adapter is retrofitted to make unrelated classes work together.
5. Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface.
6. Facade defines a new interface, whereas Adapter reuses an old interface. Remember that Adapter makes two existing interfaces work together as opposed to defining an entirely new one.
7. Which are the three main categories of design patterns?
Ans:
There are three basic classifications of patterns Creational, Structural, and Behavioral patterns.
Creational Patterns
• Abstract Factory:- Creates an instance of several families of classes
• Builder: - Separates object construction from its representation
• Factory Method:- Creates an instance of several derived classes
• Prototype:- A fully initialized instance to be copied or cloned
• Singleton:- A class in which only a single instance can exist
Note: - The best way to remember Creational pattern is by ABFPS (Abraham Became First President of States).
Structural Patterns
• Adapter:-Match interfaces of different classes.
• Bridge:-Separates an object’s abstraction from its implementation.
• Composite:-A tree structure of simple and composite objects.
• Decorator:-Add responsibilities to objects dynamically.
• Façade:-A single class that represents an entire subsystem.
• Flyweight:-A fine-grained instance used for efficient sharing.
• Proxy:-An object representing another object.
Note : To remember structural pattern best is (ABCDFFP)
Behavioral Patterns
• Mediator:-Defines simplified communication between classes.
• Memento:-Capture and restore an object's internal state.
• Interpreter:- A way to include language elements in a program.
• Iterator:-Sequentially access the elements of a collection.
• Chain of Resp: - A way of passing a request between a chain of objects.
• Command:-Encapsulate a command request as an object.
• State:-Alter an object's behavior when its state changes.
• Strategy:-Encapsulates an algorithm inside a class.
• Observer: - A way of notifying change to a number of classes.
• Template Method:-Defer the exact steps of an algorithm to a subclass.
• Visitor:-Defines a new operation to a class without change.
Note: - Just remember Music....... 2 MICS On TV (MMIICCSSOTV).
8. How can I make sure at most one instance of my class is ever created?
Ans:This is an instance where the Singleton design pattern would be used. You need to make the constructor private (so nobody can create an instance) and provide a static method to get the sole instance, where the first time the instance is retrieved it is created:
public class Mine {
private static Mine singleton;
private Mine() {
}
public static synchronized Mine getInstance() {
if (singleton == null) {
singleton = new Mine();
}
return singleton;
}
// other stuff...
}
9. What major patterns do the Java APIs utilize? Design patterns are used and supported extensively throughout the Java APIs. Here are some examples:
- The Model-View-Controller design pattern is used extensively throughout the Swing API.
- The getInstance() method in java.util.Calendar is an example of a simple form of the Factory Method design pattern.
- The classes java.lang.System and java.sql.DriverManager are examples of the Singleton pattern, although they are not implemented using the approach recommended in the GoF book but with static methods.
- The Prototype pattern is supported in Java through the clone() method defined in class Object and the use of java.lang.Cloneable interface to grant permission for cloning.
- The Java Swing classes support the Command pattern by providing an Action interface and an AbstractAction class.
- The Java 1.1 event model is based on the observer pattern. In addition, the interface java.util.Observable and the class java.util.Observer provide support for this pattern.
- The Adapter pattern is used extensively by the adapter classes in java.awt.event.
- The Proxy pattern is used extensively in the implementation of Java's Remote Method Invocation (RMI) and Interface Definition Language (IDL) features.
- The structure of Component and Container classes in java.awt provide a good example of the Composite pattern.
- The Bridge pattern can be found in the separation of the components in java.awt (e.g., Button and List), and their counterparts in java.awt.peer.
10. Can you explain singleton pattern?
- There are situations in a project where we want only one instance of the object to be created and shared between the clients. No client can create an instance of the object from outside. There is only one instance of the class which is shared across the clients. Below are the steps to make a singleton pattern:-
- Define the constructor as private.
- Define the instances and methods as static.
- Below is a code snippet of a singleton in C#. We have defined the constructor as private, defined all the instance and methods using the static keyword as shown in the below code snippet figure ‘Singleton in action’. The static keyword ensures that you only one instance of the object is created and you can all the methods of the class with out creating the object. As we have made the constructor private, we need to call the class directly.
- Figure: - Singleton in action
11. J2EE design patterns
Ans:
a)Presentation-tier patterns:
What is Intercepting Filter pattern?
Ans. Provides a solution for pre-processing and post-processing a request. It allows us to declaratively apply filters for intercepting requests and responses. For ex. Servlet filters.
What is Front Controller pattern?
Ans. It manages and handles requests through a centralized code. This could either be through a servlet or a JSP (through a Java Bean). This Controller takes over the common processing which happens on the presentation tier. The front controller manages content retrieval, security, view management and retrieval.
What is View Helper pattern?
Ans. There generally are two parts to any application – the presentation and the business logics. The “View” is responsible for the output-view formatting whereas “Helper” component is responsible for the business logic. Helper components do content retrieval, validation and adaptation. Helper components generally use Business delegate pattern to access business classes.
What is Composite View pattern?
Ans. This pattern is used for creating aggregate presentations (views) from atomic sub-components. This architecture enables says piecing together of elementary view components which makes the presentation flexible by allowing personalization and customization.
What is Service to Worker pattern?
Ans. This is used in larger applications wherein one class is used to process the requests while the other is used to process the view part. This differentiation is done for maintainability.
What is Dispatcher View pattern?
Ans. This is similar to Service to Worker pattern except that it is used for smaller applications. In this one class is used for both request and view processing.
What is Business Delegate pattern?
Ans. This pattern is used to reduce the coupling between the presentation and business-logic tier. It provides a proxy to the façade from where one could call the business classes or DAO class. This pattern can be used with Service Locator pattern for improving performance.
What is Value Object (VO) pattern?
Ans. Value Object is a serializable object which would contain lot of atomic values. These are normal java classes which may have different constructors (to fill in the value of different data) and getter methods to get access to these data. VOs are used as a course grained call which gets lots of data in one go (this reduces remote overhead). The VO is made serializable for it to be transferred between different tiers within a single remote method invocation.
b)Business tier patterns for business logic (EJB) tier
Business delegate, Value Object, Session Façade, Composite Entity, Value Object Assembler, Value List Handler, and Service Locator.
What is Session Façade pattern?
Ans. This pattern hides the complexity of business components and centralizes the workflow. It provides course-grained interfaces to the clients which reduces the remote method overhead. This pattern fits well with declarative transactions and security management.
What is Value Object Assembler pattern?
Ans. This pattern allows for composing a Value Object from different sources which could be EJBs, DAOs or Java objects.
What is Value List Handler pattern?
Ans. This pattern provides a sound solution for query execution and results processing.
What is Service Locator pattern?
Ans. It provides a solution for looking-up, creating and locating services and encapsulating their complexity. It provides a single point of control and it also improves performance.
What is Data Access Object pattern?
Ans. It provides a flexible and transparent access to the data, abstracts the data sources and hides the complexity of Data persistence layer. This pattern provides for loose coupling between business and data persistence layer.
What is EJB Command pattern?
Ans. Session Façade and EJB Command patterns are competitor patterns. It wraps business logic in command beans, decouples the client and business logic tier, and reduces the number of remote method invocations.
What is Version Number pattern?
Ans. This pattern is used for transaction and persistence and provides a solution for maintaining consistency and protects against concurrency. Every time a data is fetched from the database, it comes out with a version number which is saved in the database. Once any update is requested on the same row of the database, this version is checked. If the version is same, the update is allowed else not.
12. What all patterns are used to improve performance and scalability of the application?
Ans. VO, Session Façade, Business Delegate and Service Locator.
13. What design patterns could be used to manage security?
Ans. Single Access Point, Check point and Role patterns.
14. What design patterns do you use. Describe one you have used (not singleton)? (Hint: e.g. Builder, Factory, Visitor, Chain of Command )
15. Describe the observer pattern and an example of how it would be used? (Hint: e.g. event notification when model changes to view )