13.1 Given a scenario description with a list of issues, select the design pattern (Value Object, MVC, Data Access Object, or Business Delegate) that would best solve those issues.
13.2 Match design patterns with statements describing potential benefits that accrue from the use of the pattern, for any of the following patterns:
Value Object
MVC
Data Access Object
Business Delegate
2. 2
THE FOLLOWING SUN CERTIFIED WEB COMPONENT
DEVELOPER FOR J2EE PLATFORM EXAM OBJECTIVES
COVERED IN THIS CHAPTER:
13.1 Given a scenario description with a list of issues, select the design
pattern (Value Object, MVC, Data Access Object, or Business
Delegate) that would best solve those issues.
13.2 Match design patterns with statements describing potential
benefits that accrue from the use of the pattern, for any of the
following patterns:
Value Object
MVC
Data Access Object
Business Delegate
3. 3
Design patterns offer a proven “cookbook” answer to
resolve the problem while managing various extraneous
issues.
• Value Object pattern
• Data Access Object pattern
• Business Delegate pattern
• Model View Controller pattern
5. 5
Server Tier Components
• The web browser (Presentation tier) and web server (Web
tier) communicate by way of servlets and JSPs, and the web
server (Web tier) and application server (Server tier)
communicate by way of Enterprise Java Beans (EJBs) .
• Contained within an application server, EJBs are Java classes
that implement business services and rely on the server to
manage their life cycle and architectural services such as
security, transaction management, and persistent data
storage, to name a few
6. 6
Entity Beans
• An entity bean is a transactional object that represents
persistent data. In layman’s terms, this means it is a
special Java class that manages the inserts, updates,
deletes, and selects from a database for a particular
record.
• Usually, each entity bean represents a record in a single
table or multiple tables.
7. 7
Entity beans
Usually, application servers provide a connection-pooling mechanism to
reduce the number of unnecessary connections; pooling enables a system
to service a larger population with few instances (or connections). The result
is an increase in performance.
8. 8
Session Beans
A service or task is usually made up of several database calls. Going back to our TravelAgent
example, the act of booking a flight entails the following process:
1.Acquire available flights.
2.Reserve flight with client’s information.
3.Charge client’s credit card.
9. 9
• The first requires the application to make multiple
requests to obtain each individual field item associated to
the trip.
• the second simply has the application request a single
object containing all the necessary flight information.
• Because the second approach utilizes less bandwidth,
resulting in one network call instead of many, the
application’s performance increases.
• This particular technique utilizes the common design
pattern called the Value Object pattern.
10. 10
Value Object Pattern
• It is made up of a single class called a value object. This lightweight
class is created by an entity or session bean, populated with bean
attribute values, and passed to the client for easy access. Its structure
is as follows:
• It usually provides a variety of constructors that accept attribute values
designed to create the value object.
• The members of the value object are defined as public to eliminate the
need for “get” or “set” methods.
• If there is a need for private or protected data, “get” methods can be
provided; however “set” methods should still be avoided unless
absolutely necessary.
12. 12
Updateable (or Mutable) Value Object
• There are three ways to create mutable value objects their
class can supply any one or a combination of the following
features:
• Public variables
• Constructors
• “Set” methods
13. 13
Public variables
public class Ticket {
public double cost;
public Date purchaseDate;
public Ticket() {}
public Ticket(double cost, Date purchaseDate) {
this.cost = cost;
this.purchaseDate = purchaseDate;
}
}
14. 14
The second approach enables the user to change its
private data through the use of constructor or “set”
methods:
public class Ticket {
private double cost;
private Date purchaseDate;
public Ticket() {}
public Ticket(double cost, Date purchaseDate) {
this.cost = cost;
this.purchaseDate = purchaseDate;
}
public void setCost(double cost) {
this.cost = cost;
}
public void setDate(Date purchaseDate) {
this.purchaseDate = purchaseDate;
15. 15
Sometimes value objects are amazingly complex and have a
large number of “set” methods. In such cases, it might be
beneficial to include a setData(…) method to set all values
at once.
…
public void setData(double cost, Date purchaseDate) {
this.cost = cost;
this.purchaseDate = purchaseDate;
}
16. 16
Multiple Value Objects
• This strategy is quite common in complex application
systems. In general, session beans are more likely to use
multiple value objects as they attempt to accomplish
multiple tasks to complete a process. In such cases, each
task can reference a separate value object.
17. 17
Entity Inherits Value Object
• As its name indicates, the Entity Inherits Value Object
strategy applies only to entity beans. Its purpose is to
eliminate code duplication by having an entity bean
extend the value object class.
• This means a value object is created when an entity is
instantiated. As soon as a client utilizes the entity, the
container will populate the entity with the necessary data
values that represent the desired record.
• Instead of storing the data directly in the entity class, the
data is actually inherited from the value object.
18. 18
The benefits of this strategy are as follows:
• It eliminates code duplication within the entity and the value
object because data is stored in one location—the value object.
• It helps manage changes to the entity and value object because
the data exists in only one class rather than two.
• The less appealing aspect of this strategy is the following:
> A change to a value object can affect all its subclasses.
19. 19
Value Object Factory
The process consists of the following steps:
1. Create an interface for each value object.
2. Create a value object class to implement its respective interface.
3. Create a factory class with a constructor that takes the following
arguments: The entity bean instance intending to create the value
object The interface that identifies which value object to create
4. Instantiate the factory from within the entity to create the needed
value objects.
20. 20
public interface Ticket {
public void setCost(double cost);
public void
setPurchaseDate(Date
purchaseDate);
public double getCost();
public Date getDate();
}
public interface Airline {
public void setFlightNo(int no);
public int getFlightNo();
public class TicketVO implements
Ticket {
private double cost;
private Date purchaseDate;
// implement all the get and set
methods
}
public class AirlineVO
implements Airline {
private int flightNo;
// implement all the get and set
methods
}
21. 21
public class VoFactory {
public static final int TRIP =0;
public static final int CUSTOMER =1;
…
public VoFactory (EntityBean bean, int type) {
switch(type){
case TRIP:Field[] field =
bean.getClass().getDeclaredFields();
for (int i=0; i< field.length; i++) {
…
// use reflection to associate
// bean instance to appropriate value objects
}
break;
case CUSTOMER:
…
Break;}}}
public class TripEJB implements
EntityBean {
private Ticket ticket;
private Airline airline;
public TripEJB() {
VoFactory fact = new VoFactory(this,
VoFactory.TRIP);
}
… // All mandatory entity bean methods
}
Although this approach offers
expandability, flexibility, and
maintainability benefits, it
sacrifices performance due to
the overhead involved in using
reflection to set the variables.
22. 22
Advantages
• Reduces network traffic The Value Object pattern acts like a data
carrier and enables data to be passed between client and server by
using one remote method call. This improves network performance.
• Reduces code duplication When an entity inherits from a value
object, there is no need to include attribute data within the entity.
Instead, the members are inherited. This results in reduced code
duplication. If the Value Object Factory strategy is utilized, then the
same benefit occurs; however, you face an increase in application
complexity.
• Enables concurrent access and transactions The EJB container
offers transaction isolation levels to help manage multiple access to
the same data. An isolation level defines the degree of strictness an
application will maintain for data access. By defining the correct
isolation level, the integrity of a value object can be protected.
23. 23
Disadvantages
• Updates propagation and stale value objects When a
value object is mutable, the client could be holding on to
an instance that no longer represents the current record
state.
• Imagine multiple clients making requests to the same
record.
• If each client captures the same data and one makes a
change, all other clients will hold stale data.
• This could have negative effects as further changes might
not be warranted based on the new values.
24. 24
• Creates synchronization and version control issues
After an entity bean modifies a record in the database, it
must then save the new values to its own set of attribute
values. If more than one client simultaneously makes an
update to the same record, the bean could end up with
incorrect data.
• To solve this problem, the entity can synchronize the bean
or value object to prevent more than one thread from
accessing the same record at a time.
• The other solution is to have the value object have a time
stamp and version number attribute.
• Thus the bean can determine whether it has the latest
update.
25. 25
• Decreases network performance
Performance can decline if the data shipped
is very large.
• A value object provides the application with
the capability to transfer information by using
one remote call instead of multiple calls.
• The downside to this technique is that it
causes larger amounts of data to be shipped
in one call.
• Depending on the object size, this can
sometimes be more of a problem than a
benefit.
26. 26
Data Access Object Pattern
• Behind every large and successful application is a
strong information storage system. Most web
applications deal with stored data in one way or another.
27. 27
This pattern requires the following three
elements:
• A business object, utilizing each DAO interface and its
methods to communicate with the EIS tier
• A DAO class, providing the specific vendor
implementation for communication
• A data source, representing the data storage device
28. 28
Basic Database Access Object
• When writing an entity bean, which normally maps to a
database record,you can handle the persistence data two
ways: either the bean can provide the SQL
• —this is known as Bean Managed Persistence (BMP), or
the EJB container can generate the SQL—this is known
as Container Managed Persistence (CMP).
29. 29
Automatic Code Generated Data Access
Object
• Java reflection API, which uses introspection to
dynamically determine table names and fields that can be
mapped to each access object.
• Another example might be a tool that maps objects to
relational databases. If you are familiar with Container
Managed Persistence for an entity bean, the container
provides such a device.
30. 30
• The benefit of this strategy is that it reduces the amount
of code the developer needs to generate.
• If changes to the DAO object are updated dynamically,
the client will probably experience a runtime delay the first
time the instance is created.
• The reason for the delay is that techniques such as
introspection and reflection take time up front.
31. 31
Factory for Data Access Object
• is designed to have a class provide DAO objects for a
specific data source.
• An application calls on the factory to acquire a particular
data source DAO instance.
• When a new data source is introduced, it is added to the
factory and made available to the user through a static
method call.
32. 32
• A DAO factory interface, which defines the “create”
methods for each accessible data access method.
• A DAO factory class, which implements each factory
interface method to return an actual DAO object
• A DAO object, which is created by the factory and
passed to the client to handle data source management
33. 33
public interface DAOFactory {
public AirlineDAO
createAirlineDAO();
public HotelDAO
createHotelDAO();
public class RdbDAOFactory
implements DAOFactory {
private Connection con;
public RdbDAOFactory( String url) {
// make connection
conn = …;
}
public AirlineDAO createAirlineDAO() {
return new AirlineDAO(conn);
}
public HotelDAO createHotelDAO() {
return new HotelDAO(conn);}}
public interface AirlineDAO {
public void insert(String query);
public void delete(String query);
public void update(String query);
}
34. 34
class AirlineDAOImpl_RDB implements
AirlineDAO {
…
public AirlineDAOImpl_RDB(String source)
{
// make connection
}
public void insert(String sql) {
…}
public void delete(String sql) {
…}
public void update(String sql) {
…}…}
public class EISFactory {
public static DAOFactory
getRdbDAOFactory(String driver)
{
return new
RdbDAOFactory(driver);
}
public static DAOFactory
getOdbDAOFactory(String driver)
{return new
OdbDAOFactory(driver);
}
Create the DAO objects:
35. 35
public class Client {
public static void main(String[] args) {
DAOFactory dao =
EISFactory.getRdbDAOFactory(“com.sybex.driver”);
AirlineDAO airline = dao.createAirlineDAO();
airline.insert(…);
…
}
}
36. 36
Advantages
• Hides data access implementation code When the business object
invokes a DAO method, the actual implementation is hidden and transparent
to the client.
• Eliminates code dependencies Separating the DAO object from the
business object makes migrating to a new data source seamless. When
using factories, a change in data source affects only the Data Access Object
layer, leaving the client ignorant to the modification.
• Improves code readability and development productivity This happens
for two reasons. The first is a result of separating the business object logic
from the data access logic. Complex data manipulation code is maintained
within its own DAO object.
• The second reason the code is more readable and faster to develop is
because this pattern centralizes all data access into a separate layer.
Isolating sections of code from others can vastly improve code maintenance
37. 37
Disadvantages
• Provides more classes to manage By separating access
code into different classes, you have more classes to handle.
• Causes excessive code maintenance Sometimes
developers get overzealous about using patterns and utilize
them when they aren’t needed. For example, if it is highly
unlikely for the application to change data source types, the
factory approach might be overkill.
38. 38
Business Delegate Pattern
• It makes the client vulnerable to change. As the business
evolves, there is a good chance the business service API will
change as well with the client communicating directly with
services, the client code will also need to be changed.
• There is an impact on network performance. To look up and
access data, the client might need to make more method calls
than truly necessary.
• The client must deal with network issues associated with EJB
technology.
• For the servlet to communicate with an EJB, it must deal with
the lookup and access details of the EJB architecture.
39. 39
Business Delegate can handle:
• The naming and lookup services for EJBs
• Business service exceptions such as EJBException
• Server result caching
40. 40
Delegate Proxy
• The proxy handles the underlying tasks needed to invoke
each business method without the client needing to worry
about lookup, location, or exception information. From the
client’s perspective, it simply calls the business methods
and they “magically” work.
Delegate Adapter
is used when two systems do not use the same integration language. Let’s
say the client is written in XML and the server components are EJBs; an
adapter would be required to join the two distinct systems.
41. 41
Advantages
• Improves code manageability Code is more manageable
because client components are not directly linked to server-
side components.
• Provides easier exception handling Because the delegate
can translate business service exceptions, the client needs
to deal only with application-level issues.
• Offers a simpler business service API While a server
application might have many session beans available, the
delegate provides a clean list of available methods to the
client without worrying about which session to invoke to
access a particular behavior.
• Improves performance Because the delegate can cache
services, the Presentation tier does not need to make as
many network calls to access commonly requested data.
42. 42
Disadvantages
There are a few minor disadvantages to this pattern. They
include:
• Adds complexity By adding an extra layer, you
increase the intricacy of the application.
• Decreases flexibility The client is restricted to the
options provided by the delegate.
43. 43
Model View Controller Pattern
• The Model View Controller (MVC) pattern affects the
Presentation layer to improve the application’s
extensibility, flexibility, and manageability. MVC divides
the display logic from the code that causes change.
• its tasks into three pieces:
• The controller, which triggers a change to the component
• The model, which manages the data by providing
methods to alter or access the information
• The view, which provides a visual display of the current
data
44. 44
The benefits you gain from creating three classes, rather than two or one, are as
follows:
• Changes to the controller do not affect any view classes.
• Changes to the view do not affect any controller classes.
• You can add additional view or controller classes without affecting existing code.
45. 45
The order of operations is as follows:
1. When the controller is triggered, it communicates a
change to the model.
2. The model makes a change to the data and pushes
the new data to the appropriate views.
3. The view receives the new data and displays the new
image or form.
46. 46
Advantages
• Provides job separation Web designers can focus on
creating graphic presentations through JSPs, while code
developers can generate code to perform tasks using
servlets.
• Improves code manageability Because each task is
contained within its own object, it is easy to locate and
determine where a problem exists. This decreases the
time needed to fix errors or expand the code.