Showing posts with label J2EE Design Patterns. Show all posts
Showing posts with label J2EE Design Patterns. Show all posts

Value Object Pattern

Value Object
In this chapter, we are going to take a detailed look at the Value Object Pattern. 


What is Value Object Pattern? 
The Value Object 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. Do I have to tell you that, this is a very useful pattern? 


Is 
This 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 calls.


Is Not
This pattern is not a concrete object. You wouldn't use it to create an object. You could use it to hold values of that object.


Analogy
This would be like placing several letters in a box to be mailed once a week instead of mailing the letters separately and multiple times over the week. The box is mailed once. When the box arrives, the mail carrier can just reach in the box for the next letter; she doesn't have to contact the origin, which would take a long time. 


Problem
In J2EE, server-resident business applications often use session beans and entity beans. The session beans are responsible for functionality that is involved in one-to-one transactions with the client. In contrast, the entity beans are used to handle persistent data. So, the client will make many calls to the session bean to get data. That represents a lot of traffic, to and from a remote location because the bean may be at a server at a remote location. Likewise, the session bean may make many calls to the entity bean getting and setting attributes. The Value Object pattern encapsulates the data fields of an entity bean; VO has nothing to do with session beans (except that it is usually a session method call that returns a VO, instead of a remote entity reference). 


This activity is inefficient. We need a way to eliminate all these potential network calls reducing overhead and providing a more direct access approach.


Responsibility
This pattern provides a mechanism to exchange many remote calls to local, direct calls.


Aim
This pattern attempts to reduce the network overhead by minimizing the number of network calls to get data from the business tier.


Primary Activity
Used to collect remote data into an object that is sent to the client, so now the client makes local calls to get values rather than remote ones.


Context
Multi-tier applications that need to exchange sets of data between the client and server often.


Benefits
• J2EE applications often use enterprise beans. All calls to these beans are performed via remote interfaces to the bean due to Java's architecture. This introduces overhead.
• The frequency of reads is greater than updates because the client gets the data from the business tier for presentation.
• The client usually needs a set of data, not just one attribute.
• Client calls to enterprise beans accessed over the network affects WebApp performance because of the sum of network latency of multiple attribute access to the entity bean.
• Regardless of Java's bean architecture, it would be better to collect attributes into one object and get them from it rather than make invoking remote methods for the same information.


Usage
This pattern is useful when you need a collection of data from a remote source or, more likely, when a client has to make several calls for data from entity beans.


Consequences
• Simplifies Entity Bean and Remote Interface— Sun suggests using getData() and setData() methods on certain entity beans as a way to get and set a value object containing the set of attribute values. Calling the getData() method once replaces multiple calls to get methods. Likewise, the setData() method replaces many set calls.
• Using this pattern transfers a set of values in one method call improving overall performance, especially over the network. It represents coarse versus fine-grained interfaces.
• The client can update, delete, and read the values that are now local at will. When done, it can update the data source in one call. However, there may be a problem with synchronization as the other clients won't know about the changes until the update call. In the case of updates, there can be two conflicting update calls by two clients, so this must be synchronized somehow.


Uses
The ResultSet of JDBC is a collection of data returned from the data source resulting from a query. The data is now local in the ResultSet object so all calls to it are local rather than many calls to the data source directly.


Other Related Patterns
• Aggregate Entity that uses Value Object to get data across tiers.
• Session Façade, which is the business interface for clients of J2EE applications. This pattern often uses value objects as an exchange mechanism with participating entity beans.
• Value List Handler is another pattern that provides lists of value objects constructed dynamically by accessing the persistent store at request time.
• Value Object Assembler builds composite value objects from different data sources. The data sources are usually session beans or entity beans that may be requested to provide their data as value objects.

Access Modifiers and Specifiers in Java

Access Modifiers :
An access modifier is a Java keyword that indicates how a field or method can be accessed. Variables and methods in Java have access restrictions, described by the following access modifiers:

private: 
  • Used for most instance variables
  • private variables and methods are accessible only to methods of the class in which they are declared
  • Declaring instance variables private is known as data hiding
  • Example:  private int x;
default (this means no modifier is used):
  • Access is limited to the package in which the member is declared
  • Example:  int x; 
protected:
  •  Access is limited to the package in which the member is declared, as well as all subclasses of its class
  •  Example:  protected void setName() { . . . }
public:
  • The member is accessible to all classes in all packages.
  •  Declaring public methods is know as defining the class’ public interface.
  • Example:  public String getName() { . . . }
Java Access Specifiers :
  • Access specifiers indicates which mebmers of a class can be used by other classes
  •  We use of public, protected and private for access specifications
  •  Packeg access is used when there is no access specifier
  •  Package access means that all classes in the same package can access the member
  •  But for all other classes the member is private
You might also likefollowing tutorials:



Constructors in Java Tutorial

What is Constructor  in Java?
  • Constructor is a special method that gets invoked “automatically” at the time of object creation.
  • Constructor is normally used for initializing objects with default values unless different values are supplied.
  • Constructor has the same name as the class name.
  • Constructor cannot return values.
  • A class can have more than one constructor as long as they have different signature (i.e., different input arguments).
If Constructor  not defined in the class?
  • If you don’t define a constructor, a default one(Zero Argument constructor) will be created by Java compiler.
  • If you define any constructor for your class, no default constructor is automatically created.
Sample Examle :


public class ClassName {

    // Data Fields…

    // Constructor
    public ClassName()                  
    {
        // Method Body Statements initialising Data Fields
    }

    //Methods to manipulate data fields
}

How to call one constructor from another ?
  • We can call one constructor from another using this()
  • Use this to call other constructors in the same class.

this( ) :
  • Use this to refer to the current object.
  • Use this to invoke other constructors of the object. 
public class HelloWorld
{
 int i ;
 String str;
 HelloWorld()
 {
  this(2);
 }
 HelloWorld(int i){
  this("Hai");
  this.i = i;
 }
 HelloWorld(String str){
  this.str = str;
  System.out.println(str + "Welcome!!!!");
 }
}

How to Call Super Class constructor ?
  • we can call superclass constructor Using super() keyword
  • super needs to be the first line of code in  the constructor of the child class.
class Base
{
  Base()
 {
  System.out.println("Hello i'm a super class Zero Arg Constructor");
 }
  Base(int i)
 {
  System.out.println("Hello i'm a super class Arg Constructor");
 }
}
class Der extends Base
{
  Der()
  {
   super(); //Automatically call if you don't call constructor here.
   System.out.println("Sub class constructor");
  }
   Der(int j){
   super(4);
   System.out.println("Hai");
  }
}

Differences between method and constructor 
  • There is no return type given in a constructor signature (header). The value is this object itself so there is no need to indicate a return value.
  • There is no return statement in the body of the constructor.
  • The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.
Differences between super() and this()
  • "this" refers to the current class where as "super" refers directly to its immediate above super class.
  • this() can be used to invoke a constructor of the same class.super() can be used to invoke a super class constructor
Other Java Tutorials you may like

How to Create an AJAX object for various browsers

<script type="text/javascript">

function ajaxDataGet(){

var ajaxObject;  //the variable that will store the object

try {

   // Firefox, Safari, Chrome, Opera, Internet Explorer 7+

            ajaxObject = new XMLHttpRequest();

     }  catch (e) { 

         // Internet Explorer 5 & 6

      try {

        ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");   

          } catch (e){

          //if AJAX is not supported at all

      alert("Your browser does not support AJAX!! ");

      return false;

      }

   }

}

</script>

Roles and Responsibilities of Java EE

The Java EE platform defines different roles and responsibilities relating to development, assembly, and deployment of Java EE applications. In this book we are mainly interested in the Developer, Assembler, and Deployer roles, but we introduce you to  all the roles so that you can be familiar with them. The roles defined by the specifications are 

  • Enterprise Bean Provider 
  • Application Assembler 
  • Deployer 
  • EJB Server Provider 
  • EJB Container Provider 
  • Persistence Provider 
  • System Administrator 

      The database administrator is not one of the defined Java EE roles. The database administrator may not even understand a line of Java code. However, the importance of this role cannot be overlooked, especially in large corporations where relational databases are outside the control of the application developers. Developers, 
             Assemblers, and Deployers may need to work with the DBAs in order to successfully build and release Java EE applications. It’s all about the division of labor. Many believe that the difficulties of earlier EJB practices were a result of the division of the EJB roles. In reality, the previous EJB     specifications were not the real culprit—the source of all the confusion is the Java EE specification.

Short Definitions for all Design Patterns

What is a design pattern
a practical, proven solution to a recurring design problem

1. Creational 
2. Structural
3. Behavioral

Creational patterns are ones that create objects for you, rather than having you instantiate objects directly

Structural patterns help you compose groups of objects into larger structures

Behavioral patterns help you define the communication between objects in your system and how the flow is controlled in a complex program.


Creational Patterns Types

Factory Method : define an interface for creating an object, but let sub-class decide which class to instantiate. This lets a class to defer instantiation to subclasses.

Builder : separate the construction of a complex object from its representation so that the same construction process can create diff. representations.

Abstract Factory : provide an interface for creating families of related or dependent objects without specifying their concrete classes.

Prototype : specify the kinds of objects to create using a prototypical instance and create new objects by copying this prototype.

Singleton : Ensure a class only has one instance, and provide a global point of access to it.

Structural Patterns Types:

Adapter : convert the interface of a class into another interface clients expect. Adapter lets classes work together that could not otherwise because of incompatible interfaces.

The Adapter pattern is used so that two unrelated interfaces can work together. The joining between them is called an Adapter 

Bridge : Decouple an abstraction from its implementation so that the two can vary independently.

Composite : compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly

Decorator : Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub classing for extending functionality.

Façade : Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher level interface that makes the subsystem easier to use

Flyweight : use sharing to support large numbers of fine-grained objects efficiently.

Proxy : which provides a simple place-holder class for a more complex class which is expensive to instantiate.



Behavioral Patterns Types:

Chain of responsibility : The responsibility of handling the request data is given to any of the members of the “chain”. If the first link of the chain cannot handle the responsibility, it passes the request data to the next level in the chain, i.e. to the next link. (a chain of classes that process request )

Command : The client invokes a particular module using a command. The client passes a request, this request gets propagated as a command. The command request maps to particular modules. According to the command, a module is invoked. (request encapsulated in an object ) 

Interpreter : It converts the code written in English to a byte code format so as to make possible for all the operating systems to understand it.

Iterator : which allows you to navigate through a collection of data using a common interface without knowing about the underlying implementation.

Mediator : It promotes loose-coupling of classes such that only one class (Mediator) has the knowledge of all the classes, rest of the classes have their responsibilities and they only interact with the Mediator. 

Memento : without violating encapsulation, capture and externalize an objects' internal state so that the object can be restored to this state later. (store and restore object's internal state )

Observer : define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

State : allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
(provides a memory for a class’s instance variables.)

Strategy : Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. 
(group of classes that represent set of possible behaviors )

Template Method : define the skeleton of an algorithm in an operation, deferring some steps to subclasses. provides a method that allows sub-classes to override parts of method without re-writing it. (provides an abstract definition of an algorithm. )

Visitor : Represent an operation to be performed on the elements of an object structure. Visitor to add new function to a set of classes without having to modify them.

Request Handling Using FrontController Pattern

A very important part of the FrontController pattern is that when FrontController recieves a request will initiate the appropriate Controller (or Command,you name it!) and then delegate request to the controller.In order to do that,FrontController, must somehow retrieve from the request the name of the controller and initiate the appropriate controller class.

The first step will ne to retrieve the name of the controller from the request.
String url=request.getRequestURL().substring(request.getRequestURL().lastIndexOf("/") + 1, request.getRequestURL().length());
String controller = url.substring(0, url.indexOf("."));
In the above code snippet,url variable is assigned with the valueIndex.javastuff and controller variable is assigned with the value Index. Later on, in the ControllerFactory class -the class that instantiates and returns the Controller.Not shown in this tutorial- we construct the full name of the Controller and return a new instance of the Controller class.The below snippet shows how is this done:
try {
            String name = "com.javaonly.controllers." + className + "Controller";
            Class controllerClass = Class.forName(name);
            return (Controller)controllerClass.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
As you can see above, name variable is assigned with full name of the Cotroller class.Later on we call Class.forName method to get Cotnroller's class and finally we return a new instance.

Design Pattern Interview question and answers

What is a software design pattern?
A design pattern is a solution to a general software problem within a particular context.
Context:
A recurring set of situations where the pattern applies.
Problem:
A System of forces (goals and constraints) that occur repeatedly in this context.
Solution:
A description of communicating objects and classes (collaboration) that can be applied to resolve those forces.
Why is the study of patterns important?
As initial software designs are implemented and deployed, programmers often discover improvements which make the designs more adaptable to change. Design patterns capture solutions that have evolved over time as developers strive for greater flexibility in their software, and they document the solutions in a way which facilitates their reuse in other, possibly unrelated systems. Design patterns allow us to reuse the knowledge of experienced software designers.
3)How do I document a design pattern?
A pattern description must address the following major points:
Pattern Name and Classification
A short, meaningful name for the pattern, usually only one or two words. Names provide a vocabulary for patterns, and they have implied semantics – choose names carefully. Following the GoF book, we can also group patterns into higher level classifications such as creational, structural, and behavioral patterns.
Problem:
A general description of the problem context and the goals and constraints that occur repeatedly in that context. A concrete motivational scenario can be used to help describe the problem. The problem description should provide guidance to assist others in recognizing situations where the pattern can be applied.
Solution:
The classes and/or objects that participate in the design pattern, their structure (e.g., in terms of a UML class diagram), their responsibilities, and their collaborations. The solution provides an abstract description that can be applied in many different situations. Sample Code in an object-oriented language can be used to illustrate a concrete realization of the pattern.
Consequences:
A discussion of the results and tradeoffs of applying the pattern. Variations and language-dependent alternatives should also be addressed.
Known Uses:
Examples of the pattern in real systems. Look for applications of the pattern in language libraries and frameworks, published system descriptions, text books, etc. Not every good solution represents a pattern. A general rule of thumb is that a candidate pattern (also called a “proto-pattern”) should be discovered in a minimum of three existing systems before it can rightfully be called a pattern.
The following quote by Robert Martin highlights the importance of providing pattern descriptions: “The revolutionary concept of the GoF book is not the fact that there are patterns; it is the way in which those patterns are documented. ... Prior to the GoF book, the only good way to learn patterns was to discover them in design documentation, or (more probably) code.”
4)Where can I learn more about design patterns?
The best place to start is the seminal work by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (collectively known as the “Gang of Four” or simply “GoF”) entitled
Warning: This book is not light reading. From the Preface: “Don't worry if you don't understand this book completely on the first reading. We didn't understand it all on the first writing.”
It is, however, a book which wears well over time, and it is definitely worth the effort required to work through it.
What is an example of a design pattern?
Following the lead of the “Gang of Four” (GoF), design pattern descriptions usually contain multiple sections including
* Intent
* Motivation
* Applicability
* Structure
* Participants
* Collaborations
* Consequences
* Implementation
* Sample Code
* Known Uses
* Related Patterns
A complete discussion of even a small pattern is beyond the scope of a simple FAQ entry, but it is possible to get the idea by examining an abbreviated discussion of one of the simplest and most easily understood patterns. Consider the Singleton pattern, whose intent reads as follows:
Intent: Ensure that a class has one instance, and provide a global point of access to it.
Almost every programmer has encountered this problem and formulated an approach for solving it in a general way – some solutions are better than others. The solution offered by the GoF would look something like the following when coded in java.


Java Design Patterns Interview Questions

What are design patterns?
A pattern is a proven (and recurring) solution to a problem in a context. Each pattern describes a problem which occurs time and again in our environment, and describes its solution to this problem in such a way that we can use this solution any number of times. In simple words, there are a lot of common problems which a lot of developers have faced over time. These common problems ideally should have a common solution too. It is this solution when documented and used over and over becomes a design pattern.

Can we always apply the same solution to different problems at hand?

No. Design patterns would study the different problems at hand. To these problems then it would suggest different design patterns to be used. However, the type of code to be written in that design pattern is solely the discretion of the Project Manager who is handling that project.

What should be the level of detail/abstraction which should be provided by a design pattern?
Design patterns should present a higher abstraction level though it might include details of the solution. However, these details are lower abstractions and are called strategies. There may be more than one way to apply these strategies in implementing the patterns. The details of implementation are usually upto the developer who is coding at the ground level.

What are the most common problems which one faces during the application design phase that are solved by design patterns?

Some are:
1. Identifying components, internal structures of the components, and relationships between components.
2. Determining component granularity and appropriate interactions
3. Defining component interfaces.

How does one decide which Design pattern to use in our application?

We need to follow these steps:
1. We need to understand the problem at hand. Break it down to finer grained problems. Each design pattern is meant to solve certain kinds of problems. This would narrow down our search for design patterns.
2. Read the problem statement again along with the solution which the design pattern will provide. This may instigate to change a few patterns that we are to use.
3. Now figure out the interrelations between different patterns. Also decide what all patterns will remain stable in the application and what all need to change (with respect to Change Requests received from the clients).

What is Refactoring?

Learning different design patterns is not sufficient to becoming a good designer. We have to understand these patterns and use them where they have more benefits. Using too many patterns (more than required) would be over-engineering and using less design patterns than required would be under-engineering. In both these scenarios we use refactoring. Refactoring is a change made to the internal structure of the software to make it easier to understand and cheaper to modify, without changing its observable behaviour.

What are Antipatterns?

Though the use of patterns fulfils our objectives in the applications; there are also several instances where several applications did not fulfill their goals. The architects of these applications too need to document these wrong decisions. This helps others by preventing them from repeating these mistakes in their applications. Such documented mistakes are called antipatterns.

As we do development in tiers, how do we divide patterns in tiers?

The Sun Java Center has classified the patterns in three tiers. These are:

Presentation tier patterns for web-component tier,
Business tier patterns for business logic (EJB) tier, and
Integration tier patterns for connection to the databases.

What are the Presentation Tier Patterns? 

The presentation tier patterns are:

Intercepting filter, Front Controller, View Helper, Composite View, Service-to-Worker, and Dispatcher View.

What are the Business Tier Patterns? 

The business tier patterns are:

Business delegate, Value Object, Session Façade, Composite Entity, Value Object Assembler, Value List Handler, and Service Locator.

What are the Integration Tier Patterns? 

Integration tier patterns are:

Data Access Object (DAO) and Service Activator

What is Intercepting Filter pattern?

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?

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?

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?

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?

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?

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?

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 pattern?

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

What is Session Façade pattern?

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?

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?

This pattern provides a sound solution for query execution and results processing.

What is Service Locator pattern?

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?

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?

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?

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.

What all patterns are used to improve performance and scalability of the application?

Value Object, Session Façade, Business Delegate and Service Locator.

What design patterns could be used to manage security?

Single Access Point, Check point and Role patterns

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,
        remoteObject.getName();
        remoteObject.getCity();
        remoteObject.getState();
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();
        person.setName("Ravi");
        person.setCity("Austin");
        // send Value Object through network
        remoteObject.getPersonInfo(person);
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.

ValueObjectFactory
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. 

Singleton
à 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.


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email