Patterns in Your Solution


As mentioned, you must understand and use several patterns for this certification: most likely, Value Object, Data Access Object, Decorator, and MVC. You might also use the Front Controller and Business Delegate patterns. You can explore additional design patterns for your solution, such as Observer-Observable, in which your event-handling code in the client is the Observer and the GUI event ( user mouse click) is the Observable. You might consider the Adapter pattern, which enables you to have objects with different interfaces communicate with each other. In this case, you might use an adapter for the classes included in the assignment download because you might want to have a different interface between the GUI and the database tier .

The following sections describe each pattern in detail, using the previously listed pattern elements. Patterns are difficult to use and understand without detailed explanation. Although you might not use all these patterns, they are the ones most candidates consider for their designs.

Decorator

The Decorator pattern is used for wrapping an object with additional functionality. When you wrap an object, you are "decorating" it, in design pattern terminology. A Decorator's interface is exactly the same as the object it contains.

Is

In the Decorator pattern, an object (the "decorator") encapsulates another one (the "decoratee") and provides additional functionality. Objects calling methods of the decorator do not know it is a wrapper because its API is the same as the decoratee. The wrapper can then perform preprocessing and postprocessing before and after delegating the call to the decoratee.

Is Not

The Decorator pattern is not a way to extend a class. Normal inheritance does that well. Similar to how a class must implement methods from an implemented interface, a Decorator's methods must exist in the decoratee.

Analogy

The Decorator pattern is like the president's secretary who intercepts all calls and mail. If you send an e-mail to the president, you use his address, not knowing that someone else intercepts it. The secretary reads it, takes action on it, perhaps researches and summarizes the letter, and then finally gives the e-mail's summary to the president. The president gives a short verbal response to the secretary, who in turn replies with an official letter on behalf of the president, including proper signatures and letterhead.

Problem

Some objects need help in processing communication with a client. The current object is often generalized, so it can't be used directly without modification. This object is still responsible for certain functionality involved in one-to-one transactions with the client.

Wrapping the object with a Decorator allows the communication contract to remain intact, but method calls can now be enhanced. Without a Decorator, some objects restrict the possibility of changing behavior. Suppose you have a deeply inherited class hierarchy. You might not want to add methods to a given class. How can you make it more useful to your current application? You can wrap it.

Responsibility

The Decorator pattern provides a way to better respond to changing functionality without changing the API.

Intent (or Goals and Constraints)

The Decorator pattern attempts to add functionality to certain methods by wrapping them with another method having the same signature.

Primary Activity

The Decorator relays calls it receives to the object it contains and adds functionality before and/or after the relay.

Context

Many objects' utility can be extended through decoration. In addition, when objects outlive their usefulness , they can be reused by being decorated .

Motivation or Forces

What issues motivate you to use the Decorator pattern? The following forces apply to the Decorator pattern:

  • Many applications often use old classes. Some calls to these classes require new considerations and new functionality.

  • Although new functionality is more frequently added through subclassing, sometimes the API should not be changed.

  • Instead of growing an object through subclassing, you can grow that object through wrapping it with successive Decorators.

Applicability

The Decorator pattern is useful in your certification project because the classes provided in the assignment download are not sufficient to create a full database. In my solution, I decorated one of the classes so that the client didn't know whether the database was local or remote via RMI.

Solution

The Decorator pattern's solution consists of the following parts :

  • Strategy ” Use a Decorator to completely encapsulate another object.

  • Pseudo Code ” The code snippet in Listing 16.1 shows an example for this pattern.

Listing 16.1 The Decorator Pattern's Skeleton Program
 public class DecorateDatabase {     // public members     Database database;     // default constructor     public DecorateDatabase()     {         super();         database = new Database();     }     //other constructors     // method to set all the values     public boolean isSeatAvailable(int seatNumber)     {         boolean available = false;         // preprocessing         if (seatNumber < 0  seatNumber > 100)         {             return false;         }         // delegate to the decoratee         seatNumber = database.doStuffIfSeatAvailable(seatNumber);         // postprocessing         if (seatNumber < 20 && available==true)         {             //this is a VIP seat         }         return available;     } } public class Database {     public int doStuffIfSeatAvailable(int seatNumber)     {         int returnValue = 0;         //do something with seat available request         return returnValue;     } } 
Consequences

Using the Decorator pattern has the following consequences:

  • This pattern allows the use of legacy objects in a way that doesn't break old code.

  • Using this pattern keeps old classes alive longer.

  • The Decorator can intercept, change, and modify messages to and from the calling object.

Known Uses

The Decorator pattern can be used for Java's I/O stream implementation.

Related Patterns

The Adapter pattern is related to the Decorator pattern.

References

For more information on the Decorator pattern, consult the following site:

http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/DecoratorPattern.htm

Value Object

graphics/note_icon.gif

The Value Object pattern is now widely regarded as the Transfer Object (TO).


The Value Object pattern is the best way to exchange data across tiers or system boundaries, especially when network communication is involved. This pattern solves performance issues around network latency. You might use it in your solution to contain the results of a database query that the client initiates.

Is

The Value Object pattern describes an object that encapsulates a set of values, typically for transfer across the network. A single method call can then be used to send and receive the transfer object, rather than making a separate method call to transfer each value individually.

Is Not

The objects created via the Value Object pattern are not concrete objects. You wouldn't use it to create, for example, a car object. You could use it to hold values about a car, however, such as its color and model.

Analogy

The Value Object pattern is like placing several letters in a larger envelope and mailing the larger envelope, rather than mailing the letters separately. The mail carrier only has to deliver a single letter to the recipient rather than making multiple deliveries. When the large envelope arrives, the receiver can just reach in the envelope for the next single letter; she doesn't have to go back to the mailing origin, which would take a long time. There is one problem, however: She doesn't know whether the sender is still at the originating address after she receives the larger envelope with letters in it.

Problem

In J2EE, server-resident business applications often use session beans and entity beans. Session beans are responsible for functionality involved in one-to-one transactions with the client. Contrast that with entity beans, which are intended to handle persistent data. A client makes many calls to a session bean to get data, which could represent a lot of traffic to and from a remote location because the bean might be at a server at that location. Likewise, a session bean can make many calls to an entity bean while getting and setting attributes. The Value Object pattern encapsulates an entity bean's data fields so that a single method call can get or set the fields' values. Whether you use sockets or RMI, you probably want to encapsulate the results of a database request in a Value Object.

Without a Value Object, your GUI would have to make many requests to the database, an inefficient approach. You need a way to eliminate these extra network calls to reduce overhead and provide a more direct access approach.

Responsibility

The Value Object pattern provides a mechanism for exchanging many remote calls to local, direct calls.

Intent (or Goals and Constraints)

The Value Object pattern attempts to reduce network overhead by minimizing the number of network calls to get data from the business tier.

Primary Activity

The Value Object pattern is used to collect remote data into an object that is sent to the client. The client can then make local calls to this object's methods rather than remote ones to get values.

Context

The Value Object pattern can be used in multitier applications that often need to exchange sets of data between the client and server.

Motivation or Forces

The following issues and motivations justify the use of the Value Object pattern:

  • J2EE applications often use Enterprise JavaBeans. Because of Java's architecture, all calls to these beans are performed via remote interfaces to the bean. Even without EJB, many client/server applications require repeated retrieval of data, which introduces overhead.

  • The frequency of reads is higher than updates because the client gets data from the business tier for presentation.

  • The client usually needs a set of data, not just one attribute.

  • A large number of client calls to the data tier across the network can adversely impact your solution's performance.

  • Regardless of your architecture, it would be best to collect attributes into one object and place that object close to the GUI for local inspection instead of calling remote methods for the same information.

Applicability

The Value Object pattern is useful when you need a collection of data from a remote source or, more likely, when a client in remote mode has to make several calls for data from the database.

Solution

The Value Object pattern provides a solution consisting of the following parts:

  • Strategy ” Use a Value Object to encapsulate a collection of data so that it takes only one call to get or set the collection.

  • Pseudo Code ” The code snippet in Listing 16.2 shows an example for this pattern.

Listing 16.2 The Value Object Pattern's Skeleton Program
 public class CustomerOrder implements java.io.Serializable {     // private members     private int accountNumber;     private int customerID;     private int orderNumber;     private float orderAmount;     // default constructor     public CustomerOrder() {}     // constructor accepting data values     public CustomerOrder(int customerID,                          int accountNumber,                          int orderNumber,                          float orderAmount)     {        init(customerID, accountNumber,             orderNumber, orderAmount);     }     // constructor to create a new Value Object based     // using an existing Value Object instance     public CustomerOrder(CustomerOrder contact)     {         init (contact.customerID,         contact.accountNumber, contact.orderNumber,         contact.orderAmount);     }     // method to set all the values     public void init(int customerID,                      int accountNumber,                      int orderNumber,                      float orderAmount)     {         this.customerID = customerID;         this.accountNumber = accountNumber;         this.orderNumber = orderNumber;         this.orderAmount = orderAmount;     }     // create a new Value Object     public CustomerOrder getData()     {         return new CustomerOrder(this);     }     // get new values     public boolean setData()     {            boolean success = false;            //get data from database            //which sets the success flag             return success;     }     /*     add: get and set methods for customerID,     accountNumber, orderNumber, and orderAmount.     */ } 
Consequences

Using the Value Object pattern has the following consequences:

  • This pattern simplifies data flow by using getData() and setData() methods as a way to get and set attributes in a Value Object. Calling the local getData() method once replaces a remote call ( potentially multiple calls) to methods over the network.

  • Using this pattern transfers a set of values in one method call, which improves overall performance, especially over the network. This pattern represents coarse-grained versus fine-grained interfaces.

  • The client can freely update, delete, and read values that are now local. When it's done, it can update the data source in one call. However, there might be a problem with synchronization, as other clients won't know about changes until the update call. It's possible to have two conflicting update calls by two clients , so this conflict must be synchronized somehow.

Known Uses

The ResultSet object in Java Database Connectivity (JDBC) is a collection of data (resulting from a query) returned from a data source. The data is now local in the ResultSet object, so all calls to it are local instead of many direct calls to the data source.

Related Patterns

The following patterns are related to the Value Object pattern. For more information, visit this site:

http://developer.java.sun.com/developer/technicalArticles/J2EE/patterns/J2EEPatternsRelationships.html

  • Aggregate Entity pattern ” Thispattern uses a Value Object to get data across tiers.

  • Session Facade pattern ” This pattern 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 pattern ” This pattern is another one that provides lists of Value Objects constructed dynamically by accessing the persistent store at request time.

  • Value Object Assembler patter n ” This pattern builds composite Value Objects from different data sources. The data sources are usually session beans or entity beans that can be requested to provide their data as Value Objects.

References

The following page is available only to registered members of the Java Developer connection:

http://developer.java.sun.com/developer/restricted/patterns/

Data Access Object

The Data Access Object (DAO) pattern provides a connection between the business logic tier and the resource (usually database or file) tier. The DAO abstracts and encapsulates all access to the data source, completely hiding the data source's implementation details from the business components that use the DAO.

While the DAO may access resources via JDBC, CORBA IIOP (Internet Inter-Orb Protocol), RMI, low-level sockets, and other means, the business object only has to be concerned with the (usually simpler) interface of the DAO. At such time as the underlying data source changes, the DAO's code may change, but its interface will not, thus ensuring that no changes are necessary to the business components that rely on the DAO.

You might want to apply this pattern to your solution so that the GUI has a clean interface to the database.

Is

The DAO pattern is an object that encapsulates a set of behaviors for accessing databases, files, and other resources. This way, you have only one API to deal with instead of a different one for each type of resource.

Is Not

The DAO pattern is not a pattern for a resource. It isn't a way to build a database or file manager, in other words.

Analogy

The DAO pattern is like using an ATM machine. The same interface fetches information requested from the back end. The user interface is a simple screen with buttons for conducting a transaction. Similarly, the DAO object presents a simple API to conduct transactions.

Problem

Applications often need to use persistent data. This data persists in many forms, such as files, relational databases, XML storage, and other types of repositories. All these stores have different APIs. Interfacing with so many APIs presents a problem when designing clients.

Responsibility

The DAO pattern provides a uniform API to any persistent data storage.

Intent (or Goals and Constraints)

The DAO pattern attempts to consolidate data access from a complex source (or set of sources) to one object. This consolidation reduces network overhead by minimizing the number of network calls to get data, but reducing network traffic is not the pattern's primary intent.

Primary Activity

The DAO pattern is used for getting and setting data from and to a permanent data source.

Context

The DAO pattern is used when access methods to data vary between types of storage and vendor.

Motivation or Forces

Various parts of an application require access to persistent stores, such as databases and files. APIs for different types of stores (even for different vendors of the same storage type) are inconsistent. To access these disparate data sources, you need a tier with a uniform API.

Applicability

The DAO pattern can be used in any application that requires access to several data source types or even an application that accesses only one but might switch in the future. The SQL code is encapsulated in the method. That way, if the SQL or data source changes, very little code rewriting is needed because the API remains constant.

Solution

The DAO pattern's solution consists of the following parts:

  • Strategy ” Use this pattern to design a Data Access Object that abstracts the access API to various data sources.

  • Pseudo Code ” The DAO pattern example in Listing 11.3 is brief. The real class would likely have more SQL, but it does represent an interface that defines the API for a single DAO entity and uses an Abstract Factory pattern to create the necessary implementation objects at runtime.

Listing 16.3 The DAO Pattern's Skeleton Program
 import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Collection; /**  * This class is an example of DAO because  * it encapsulates the SQL calls made by other objects.  * This tier maps the relational data stored in the  * database to the objects needed by another tier.  */  public class CustomerDAO  {      private Connection con;      public CustomerDAO(Connection con)      {          this.con = con;      }      public CustomerOrder getCustomer(int customerId) throws SQLException      {          String sql = "select customerid, firstName, " +                       "lastName, from CUSTOMER_TABLE " +                       "where customerid = " + customerId;          Statement stmt = con.createStatement();          ResultSet rs = stmt.executeQuery(sql);          CustomerOrder cus = null;          while (rs.next())          {                 int i = 1;                 String itemid = rs.getString(i).trim();                 int accountNumber = rs.getInt(i);                 int orderNumber = rs.getInt(i);                 float orderAmount = rs.getFloat(i);                 i++;                 //new CustomerOrder object                 cus = new CustomerOrder(customerId,                                     accountNumber,                                     orderNumber,                                     orderAmount);                 //do something with cus          }         rs.close();         stmt.close();         return cus;     }     public Order getOrder(String orderid) throws SQLException     {         //this SQL string included a reference to a         //DatabaseNames object (not shown),         //which has a list of the database object         //names, including tables.         Order order = new Order();         String sql =             "select itemid, listprice, unitcost, " +             "name, descn " +             "from ITEM_TABLE, ORDER_TABLE where "+             "orderid = '" + orderid + "'";         //your DAO can have any number of attributes.         //here, the itemid and other attributes are         //how you could represent an order.         Statement stmt = con.createStatement();         ResultSet rs = stmt.executeQuery(sql);         while (rs.next())         {             int i = 1;             String itemid = rs.getString(i).trim();             double listprice = rs.getDouble(i);             double unitcost = rs.getDouble(i);             String name = rs.getString(i);             String descn = rs.getString(i);             order.add(itemid, listprice, unitcost, name, descn);             i++;         }         order.process();         rs.close();         stmt.close();         return order;     } } public class Order {     String itemid = "";     double listprice = 0;     double unitcost = 0;     String name = "";     String descn = "";     public void add(String itemid,                          double listprice,                          double unitcost,                          String name,                          String descn)     {         this.itemid = itemid;         this.listprice = listprice;         this.unitcost = unitcost;         this.name = name;         this.descn = descn;     }     public void process()     {         //process order     } } 
Consequences

Using the DAO pattern has the following consequences:

  • Clients and components can then access data with the same API, which makes the variety of sources transparent and reduces complexity.

  • It makes changing data sources easy and reduces errors.

Known Uses

At one level, JDBC uses an Abstract Factory technique to provide one API to many databases and types of files ”the very essence of this pattern. However, the emphasis Sun places on this pattern is on creating objects that encapsulate the SQL so that the client that calls a DAO is shielded from the database's structure (and thus the specific SQL queries needed for accessing data).

Related Patterns

Sun uses the GoF's Abstract Factory pattern for Data Access Object strategies. Sun bases this pattern on the abstract factory approach.

References

For more information on the DAO pattern, consult the following site:

http://java.sun.com/blueprints/patterns/DAO.html

Business Delegate

The Business Delegate pattern reduces coupling between presentation-tier clients and business services. By hiding the complexity of the business service from the client, the business delegate can shield presentation-tier clients from changes in the API of the underlying business service.

Is

The Business Delegate pattern is a proxy that hides the complexity of remote service lookup and error recovery. It makes it easier to communicate requests and results from one tier to another.

Is Not

The Business Delegate pattern is not a pattern for a tier. It isn't a way for you to create a business logic component or structure. Rather, it is an interface to a tier, so you can change the underlying components and not disturb the presentation tier.

Analogy

The Business Delegate pattern is like an ambassador to a foreign country. Regardless of government changes in the ambassador's home country, the ambassador and how she interacts with the foreign country can remain the same. In addition, the ambassador shields the foreign country from her home country's internal decision-making processes.

Problem

A dependency on a remote service increases the likelihood of change between the caller and the called. How can you reduce the chances of the tier that depends on the remote service breaking should the remote service change? The Business Delegate pattern helps protect the local tier from changes made to the remote service. Perhaps the presentation tier interacts directly with a remote business logic tier. What if the business services change and the old API becomes invalid? If this happens, the presentation tier will break.

Responsibility

The Business Delegate pattern is the proxy between the local tier and the remote service tier. It is responsible for reliably allowing the front-end tier to access the remote service.

Intent (or Goals and Constraints)

The Business Delegate pattern isolates the presentation tier from changes in the business-tier API.

Primary Activity

The Business Delegate pattern matches presentation component calls to the correct business-tier methods.

Context

The current approach to multitier systems is to couple the presentation tier directly to the entire business service API; sometimes this coupling is made across a network.

Motivation or Forces

The following forces or issues are what motivate the use of this pattern:

  • Presentation-tier clients (including devices) need access to business services.

  • The business-tier API might change.

  • The industry trend for large systems is to minimize coupling between presentation-tier clients and the business service API. This isolates the two so that the middle tier can manage a change in either side.

  • There is a need for a cache between tiers.

  • This pattern adds more work to building a system, so consider whether this extra tier is really necessary.

Applicability

Large systems change components often. There is often a change in the business tier that breaks the access portion of clients.

Solution

The Business Delegate pattern provides advantages in a design. Its solution consists of the following parts:

  • Strategy ” Sun says, "Use a Business Delegate to reduce coupling between presentation-tier clients and business services. The Business Delegate hides the underlying implementation details of the business service, such as lookup and access details of the EJB architecture."

  • Sample Code ” Visit Sun's definition of the Business Delegate pattern at http://java.sun.com/blueprints/corej2eepatterns/Patterns/BusinessDelegate.html. In the section titled "Sample Code" ( roughly 70% down the page) there is an excellent example of implementing the business delegate pattern.

Consequences

Using the Business Delegate pattern has the following consequences:

  • Caching is always good between parts that exchange a lot of data.

  • This pattern changes the interface with the intent of making the API more stable from the presentation-tier perspective.

  • This pattern can handle any exceptions, whether from the business tier or from the plumbing between the business tier and the requester.

  • This pattern isolates the presentation and business tiers from each other by adding a director between the two, making it easier to manage changes on either side.

Known Uses

The Business Delegate pattern has the following uses:

  • B2B systems usually use an XML exchange for communicating between disparate systems. Even if the internal business processes of these systems change, the XML document types used for data exchange remain the same.

  • Proxy services represent this pattern.

  • Lookup services usually represent this pattern.

Related Patterns

The following patterns are related to the Business Delegate pattern:

  • Service Locator pattern ” This pattern provides a common API for any business service lookup and access code.

  • Proxy pattern ” Provides a stand-in for objects in the business tier.

  • Adapter pattern ” You can use this pattern to provide coupling for disparate systems.

References

For more information on the Business Delegate pattern, consult the following site:

http://java.sun.com/blueprints/patterns/BusinessDelegate.html

Model-View-Controller (MVC)

The Model-View-Controller (MVC) architecture compartmentalizes the data and business logic (Model portion) from the presentation (View portion) and from the user action interpreter (Controller portion). This pattern is mandatory for your solution. Swing components are designed with MVC, so you don't have to do much to take advantage of this powerful pattern. It is a matter of telling the evaluator that you recognize the pattern and leveraged it in your GUI. For example, the instructions most likely require a JTable component. The viewable grid is the View portion. The Model portion acts as the table model. (For more information, see the JTable section in Chapter 7, "Databases and Atomicity.") The code you write that responds to JTable events is the Controller portion.

Is

The MVC pattern is a clear functional separation of roles. It is a formalization of the data-business-presentation movement that has dominated three-tier architectures over the past decade .

Is Not

The MVC pattern is very abstract. It is not simply a front end to a data source.

Analogy

The MVC pattern is like an automobile. The speed of a car is affected by the accelerator pedal (Controller), the speed is shown by the speedometer (View), and the speed is manifested by the engine (Model).

Problem

Different views of the same data are a common need. Conversely, the same client needs access to different models.

Responsibility

The MVC pattern carefully manages communication between the client and model data and functionality. It must allow changing the client or the model with minimal impact on the system.

Intent (or Goals and Constraints)

The main goal is separation of concerns. The MVC pattern attempts to minimize the impact of changing any of the three responsibilities, including Model, View, and Controller.

Primary Activity

The MVC pattern decouples views from data and business logic; MVC interjects a Controller between them, which interprets user actions into operations on the business logic and selects the next view to send to the user.

Context

An application is expected to support varying client and business logic tiers.

Motivation or Forces

The following forces or motivations are the most common reasons designers use this pattern:

  • Various clients and data models are being developed, and the two tiers need to talk to each other.

  • Non-interface-specific code is duplicated in many applications.

  • The same enterprise data is accessed by different views ”for example, HTML, Wireless Markup Language (WML), JFC/Swing, and XML. Note that different views of the data can simply be different slices of the data, rather than the data having to be in multiple formats.

  • The same enterprise data is accessed (requested, modified, and deleted) from various actions (such as HTML links, JFC/Swing events, and SOAP XML calls).

Applicability

Although the MVC pattern's primary purpose is building GUIs, it can be used to establish an analogous notification protocol between nonvisual objects. The Observer and Observable objects in java.util were designed with this pattern in mind.

Solution

What can this pattern accomplish? The MVC pattern's solution consists of the following parts:

  • Strategy ” Use the Model-View-Controller architecture to decouple presentation from core data access functionality. Also, this pattern enables you to control communication between them so that multiple views can see the same enterprise data model, or multiple data models can present the same view.

  • Pseudo Code ” MVC is used for many things. For example, it has been used for Swing components to build user interfaces, in which Sun uses the Model as the underlying logical representation, the View as the visual representation, and the Controller as the part that handles user input. When a Model changes (the user modifies text in a text field, for example), it notifies all views that depend on it (listeners). This enables you to present a single set of data in list, table, or simple text presentations. As you update the data model, the Model notifies both views and gives each an opportunity to update itself. In this architecture, the Controller determines which action to take when the user alters the model (for example, by typing text into a field). Please see http://developer.java.sun.com/developer/onlineTraining/GUI/Swing2/shortcourse.html#JFCMVC for more information.

Consequences

Using the MVC pattern has the following consequences:

  • Clients access a Controller, which accesses the model instead of the data directly.

  • Another tier has to be built, which adds work.

  • It is easier to break a project into pieces because both View and Model developers are targeting the Controller API.

Known Uses

Java uses the MVC pattern for Java Foundation Classes (JFC) and Swing. Also, Struts and Velocity use this pattern as their underlying framework. Struts is a flexible control layer based on standard technologies, such as Java servlets, JavaBeans, ResourceBundles, and Extensible Markup Language (XML). You can read more about this at http://jakarta.apache.org/struts. Velocity is a Java-based template engine providing a template language to reference objects defined in Java code. You can see more about it at http://jakarta.apache.org/velocity.

Related Patterns

MVC is a very high-level and abstract pattern compared to other patterns, so it has few related patterns.

References

For more information on the MVC pattern, consult the following site:

http://java.sun.com/blueprints/patterns/MVC.html

Front Controller

The Front Controller pattern presents one entry point to an application, such as a Web site or service. This centralized entry point controls and manages requests and eliminates a user's dependency on a direct resource. Suppose you wanted to get the latest version of the servlet specification. You would be better off going to a central page presenting options that change over time than bookmarking the servlet specification directly, as that link could be quickly outdated . Some candidates might use this pattern in a single controller (such as a front end to the database) to handle all user requests from multiple clients.

Is

The Front Controller pattern is a presentation controller that allows a resource to change without breaking bookmarks to that resource. Many sites use this pattern. This pattern is used in Struts, where all requests go to a common front controller servlet, regardless of the action requested. The MSDN site uses a similar pattern via http://msdn.microsoft.com/library/default.asp. At this site all requests go to a single ASP page, which controls what documents get displayed in each frame. Watch the address field in your browser as you surf and you'll see that almost all the MSDN URLs point to this ASP.

Is Not

The Front Controller pattern is not a pattern for a data storage viewer, and it isn't a way for you to control data retrieval. Rather, it is a steady interface to underlying resources that behaves as the presentation tier.

Analogy

The Front Controller pattern is like a travel agent. On every trip, you start by stopping at the agency. You tell the agent where you want to go, and she takes care of the arrangements. The actual flight, train, bus, and hotel details change between trips, but she always gets you there.

Problem

When a user accesses resources directly without going through a centralized mechanism, the resource might have moved. Also, each view is on its own and required to provide its own system services. Last, each view has to provide navigation, but this is a problem, as the view doesn't know about the context or the overall site.

Responsibility

The Front Controller must delegate a request to the proper resource and view.

Intent (or Goals and Constraints)

The Front Controller pattern isolates actual resources from a user's direct access.

Primary Activity

The Front Controller pattern matches the correct resource to the request.

Context

Simplified Web sites expose all their resources directly. As a site grows, decoupling navigation from resources is often better. A controller that manages requests and decides which resource best satisfies a request is necessary.

Motivation or Forces

The following forces are the primary reasons for using this pattern:

  • It is better to have a central controller allocate shared resources than to have individual resources fend for themselves independently.

  • The location of resources can change.

  • This pattern adds only a little more work to building a front end to a service, such as a database server or a Web site.

  • Multiple resources share common needs, such as security (that is, authentication and authorization).

Applicability

Databases and Web sites especially benefit from a Front Controller.

Solution

The Front Controller pattern's solution consists of the following parts:

  • Strategy ” Sun says, "Use a Controller as the initial point of contact for handling a request. The Controller manages the handling of the request, including invoking security services such as authentication and authorization, delegating business processing, managing the choice of an appropriate view, handling errors, and managing the selection of content-creation strategies."

  • Sample Code ” This pattern can be used to centralize processing requests and selecting views. For example, the MainServlet class is the Front Controller for Sun's Java Pet Store sample application Web site. All requests ending with *.do are sent through the MainServlet class for processing. Please see http://java.sun.com/blueprints/code/jps131/src/com/sun/j2ee/blueprints/waf/controller/web/MainServlet.java.html for the source code for MainServlet. Please see http://java.sun.com/blueprints/code/jps131/docs/ for the Java Pet Store Demo sample application home page.

Consequences

Using the Front Controller pattern has the following consequences:

  • Caching is always good between parts that exchange a lot of data.

  • This pattern changes an interface with the intent of making the API more stable from the presentation tier perspective.

  • This pattern now handles any exceptions, whether from the business tier or from the plumbing between the business tier and the requester.

  • This pattern isolates the presentation and business tiers by adding a mediator between the two, making it easier to manage changes on either side.

Known Uses

The Front Controller pattern has the following uses:

  • Servlet Front Strategy ” This pattern is implemented as a servlet, which manages aspects of request handling related to business processing and control flow. Because this strategy is not specifically related to display formatting, implementing this component as a JSP page is a bad idea. Also, Struts is an example of this pattern.

  • Command and Controller Strategy ” This strategy provides a generic interface to helper components. The Controller delegates responsibility to the helper components, which minimizes coupling among these components.

  • Logical Resource Mapping Strategy ” In this case, users request logical names rather than physical locations. This way, the physical location can be dynamically mapped to the logical names, say, in a database or XML document.

Related Patterns

The following patterns are related to the Front Controller pattern:

  • View Helper pattern ” The Front Controller pattern is combined with the View Helper pattern to provide containers for factoring business logic out of the view and to provide a central point of control and dispatch. Logic is factored forward into the Front Controller and back into the View Helper object.

  • Service to Worker pattern ” This pattern is the result of combining the View Helper pattern with a Dispatcher, in coordination with the Front Controller pattern.

  • Dispatcher View pattern ” This pattern combines the Front Controller and View Helper patterns with a Dispatcher component. Although this pattern and the Service to Worker pattern share the same structure, the two patterns have a different division of labor among components.

References

For more information on the Front Controller pattern, consult the following site:

http://java.sun.com/blueprints/corej2eepatterns/Patterns/FrontController.html



JavaT 2 Developer Exam CramT 2 (Exam CX-310-252A and CX-310-027)
JavaT 2 Developer Exam CramT 2 (Exam CX-310-252A and CX-310-027)
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 187

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net