Wednesday, October 31, 2012

Useful J2EE Design Patterns

Q) What is a Desin Pattern? Why use patterns?
A) A pattern describes a proven solution to a recurring design problem. Patterns provide a ready-made solution that can be adapted to different problems as necessary.

Q) J2EE Design Patterns?
Dispatcher View: Combines a Dispatcher component with the Front Controller and View Helper patterns, deferring many activities to View processing.

Service to Worker: Combines a Dispatcher component with the Front Controller and View Helper patterns.

Transfer Object Assembler: It is used to build the required model or submodel. The Transfer Object Assembler uses Transfer Objects to retrieve data from various business objects and other objects that define the model or part of the model.

Composite Entity :It model, represent, and manage a set of interrelated persistent objects rather than representing them as individual fine-grained entity beans. A Composite Entity bean represents a graph of objects.

Service Activator: Service Activator enables asynchronous access to enterprise beans and other business services. It receives asynchronous client requests and messages. On receiving a message, the Service Activator locates and invokes the necessary business methods on the business service components to fulfill the request asynchronously. In EJB2.0, Message Driven beans can be used to implement Service Activator for message based enterprise applications. The Service Activator is a JMS Listener and delegation service that creates a message façade for the EJBs.

Q) What is architectural design pattern?
A) Describe MVC2 & Front Controller.

Front Controller
 It will dispatch the request to the correct resource, Centralized controller for managing and holding of a request.

Service Locator
To access different resources/services, J2EE compatible server binds these resources/services to the JNDI server so that the clients can lookup those resources/services through JNDI lookup process from anywhere in the network. The resources/services can be
                1. EJBHome objects    2. DataSource objects               3. JMS ConnectionFactory   4. JMS Topic/Queue etc.
All these services need to bind to the JNDI services and the clients need to lookup JNDI to get those services. Clients have to go through JNDI lookup process every time to work with these services. JNDI lookup process is expensive because clients need to get network connection to the JNDI server if the JNDI server is located on a different machine and need to go through lookup process every time, this is redundant and expensive.

The solution for the redundant and expensive JNDI lookup process problem is to cache those service objects when the client performs JNDI lookup first time and reuse that service object from the cache second time onwards for other clients. This technique maintains a cache of service objects and looks up the JNDI only first time for a service object.

Session Façade
EJB clients (swing, servlets, jsps etc) can access entity beans directly. If EJB clients access entity beans directly over the network, it takes more network calls and imposes network overhead.          
Here the servlet calls multiple entity beans directly to accomplish a business process, thereby increasing the number of network calls.
The solution for avoiding number of network calls due to directly accessing multiple entity beans is to wrap entity beans with session bean (Facade). The EJB client accesses session bean (Facade) instead of entity beans through coarse grained method call to accomplish a business process.

Message Facade
Session bean and entity bean methods execute synchronously that means the method caller has to wait till a value is returned. In some situations like sending hundred's of mails or firing a batch process or updating processes, the client does not have to bother about return value. If you use synchronous session and entity beans in such situations, they take a long time to process methods and clients have to wait till the method returns a value.

The client has to wait till all the eight synchronous steps complete. This synchronous execution takes a long time and has an impact on performance when the method process is huge.

To avoid blocking of a client, use asynchronous message driven beans, so that client does not have to wait for a return value. If a client uses asynchronous messaging then the client need not wait for a return value but can continue its flow of execution after sending the message.

Value Object (DTO-DataTransfer Object)
When a client calls a remote method there will be process of marshalling, network calls and unmarshalling involved for the remote method invocation. If you choose fine-grained approach when calling methods remotely, there will be a significant network overhead involved. For example if you call fine grained method like this,
there are three network calls from client to the remote object because every method call is remote method call.

The solution for avoiding many network calls due to fine-grained method calls is to use coarse-grained approach. For example:
        // Create a Value Object and fill that object locally
        PersonInfo person = new PersonInfo();
        // send Value Object through network
Here, there is only one network call instead of three network calls and PersonInfo object is a Value Object. The following figure illustrates the coarse grained approach that is passing a Value Object through network.

Value Object is an object that is passed over the network rather than passing each attributes separately thus increasing performance by reducing network calls.

For a single request, a client might need to access multiple server side components such as different session beans and entity beans. In such situations the client accesses multiple components over the network, this increases the network traffic and has an impact on the performance.

To reduce the network traffic due to accessing multiple components by a client for a single request, let ValueObjectFactory hold different ValueObjects as placeholders and respond with a single ValueObject for a client request.

Value List Handler (DAO)

J2EE applications generally have the search facility and have to search huge data and retrieve results. If an application returns huge queried data to the client, the client takes long time to retrieve that large data and If that application uses entity bean to search data, it has an impact on.

1. Use Data Access Objects (DAO) rather than Entity beans
2. Return small quantity of data multiple times iteratively rather than returning large amount of data at once to the client.
DAO encapsulates JDBC access logic. ValueListHandler caches list of Value objects that are retrieved through DAO. When client wants to search data, It calls ValueListHandler that is in turn responsible for caching data and returning data to the client iteratively. 

à You can achieve this by having the private constructor in the class, so that other classes can't create a new instance. Its intent is to ensure that a class has only one instance, and to provide a global point of access to it. There are many situations in which a singleton object is necessary: a GUI application must have a single mouse, an active modem needs one and only one telephone line, an operating system can only have one window manager, and a PC is connected to a single keyboard

1.Create a Private constructor, so that outside class can not access this constructor. And declare a private static reference of same class.
2.Write a public Factory method which creates an object. Assign this object to private static Reference and return the object

public class Singleton
private static Singleton ref;
    private Singleton (){
    public static Singleton getSingleton()
      if (ref == null)
          ref = new Singleton ();
      return ref;

Business Delegate
The B.D acts as a client-side business abstraction and hides the implementation of the business services. such as lookup & access details of the EJB architecture.
The delegate may cache results and references to remote business services. Caching can significantly improve performance, because it limits unnecessary and potentially costly round trips over the network.
B.D uses a component called the Lookup Service. The Lookup Service is responsible for hiding the underlying implementation details of the business service lookup code.
The client requests the BusinessDelegate to provide access to the underlying business service. The BusinessDelegate uses a LookupService to locate the required BusinessService component.

Q). Where do you use singleton pattern and why?
A) If I require a single instance of an object in a particular JVM, ex while designing database connection pool. I would require a single connection object for all the users coming in, not a separate one for each user.

Q). Why Factory Pattern is used and an example?
A) Factory pattern is used in place where the implementation varies over time. Factory pattern suggest creating many different instances from interfaces. Interfaces are the one that faces client and implementation of those methods come from factory depending on a specific condition.
     ex: If the OS is Windows, look and feel of the application changes to Window style, for Linux it is Metal and for machintosh it will be different.
Q). Where do you use visitor pattern and why?
A) If I want to defrag business logic in different sets of modules and the final processing requires all these module to be included in a particular fashion. Visitor pattern generally calls a visit method of these modules /objects and
all the different logic stored in different modules and call one by one. It is something like visiting many modules one at a time.
Q). What problem an observer pattern solves?
A) If a particular event has to be notified to many objects, and list grows over time and it is hardly possible to call /notify each and every listeners at design time. We use observer pattern , just to register many objects listening to a particular event and getting notified automatically, as and when the event occurs.
Q) What is the difference between J2EE design patterns and the Gang of Four patterns?
A) The GOF design patterns apply generically to any object-oriented programming language. J2EE design patterns address common problems encountered in designing J2EE architecture. This course presents the key J2EE design patterns required when implementing a J2EE system.

No comments:

Post a Comment