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. DecoratorThe 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. IsIn 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 NotThe 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. AnalogyThe 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. ProblemSome 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. ResponsibilityThe 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 ActivityThe Decorator relays calls it receives to the object it contains and adds functionality before and/or after the relay. ContextMany objects' utility can be extended through decoration. In addition, when objects outlive their usefulness , they can be reused by being decorated . Motivation or ForcesWhat issues motivate you to use the Decorator pattern? The following forces apply to the Decorator pattern:
ApplicabilityThe 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. SolutionThe Decorator pattern's solution consists of the following parts :
Listing 16.1 The Decorator Pattern's Skeleton Programpublic 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; } } ConsequencesUsing the Decorator pattern has the following consequences:
Known UsesThe Decorator pattern can be used for Java's I/O stream implementation. Related PatternsThe Adapter pattern is related to the Decorator pattern. ReferencesFor more information on the Decorator pattern, consult the following site: http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/DecoratorPattern.htm Value Object
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. IsThe 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 NotThe 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. AnalogyThe 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. ProblemIn 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. ResponsibilityThe 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 ActivityThe 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. ContextThe Value Object pattern can be used in multitier applications that often need to exchange sets of data between the client and server. Motivation or ForcesThe following issues and motivations justify the use of the Value Object pattern:
ApplicabilityThe 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. SolutionThe Value Object pattern provides a solution consisting of the following parts:
Listing 16.2 The Value Object Pattern's Skeleton Programpublic 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. */ } ConsequencesUsing the Value Object pattern has the following consequences:
Known UsesThe 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 PatternsThe 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
ReferencesThe following page is available only to registered members of the Java Developer connection: http://developer.java.sun.com/developer/restricted/patterns/ Data Access ObjectThe 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. IsThe 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 NotThe DAO pattern is not a pattern for a resource. It isn't a way to build a database or file manager, in other words. AnalogyThe 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. ProblemApplications 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. ResponsibilityThe 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 ActivityThe DAO pattern is used for getting and setting data from and to a permanent data source. ContextThe DAO pattern is used when access methods to data vary between types of storage and vendor. Motivation or ForcesVarious 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. ApplicabilityThe 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. SolutionThe DAO pattern's solution consists of the following parts:
Listing 16.3 The DAO Pattern's Skeleton Programimport 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 } } ConsequencesUsing the DAO pattern has the following consequences:
Known UsesAt 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 PatternsSun uses the GoF's Abstract Factory pattern for Data Access Object strategies. Sun bases this pattern on the abstract factory approach. ReferencesFor more information on the DAO pattern, consult the following site: http://java.sun.com/blueprints/patterns/DAO.html Business DelegateThe 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. IsThe 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 NotThe 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. AnalogyThe 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. ProblemA 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. ResponsibilityThe 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 ActivityThe Business Delegate pattern matches presentation component calls to the correct business-tier methods. ContextThe 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 ForcesThe following forces or issues are what motivate the use of this pattern:
ApplicabilityLarge systems change components often. There is often a change in the business tier that breaks the access portion of clients. SolutionThe Business Delegate pattern provides advantages in a design. Its solution consists of the following parts:
ConsequencesUsing the Business Delegate pattern has the following consequences:
Known UsesThe Business Delegate pattern has the following uses:
Related PatternsThe following patterns are related to the Business Delegate pattern:
ReferencesFor 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. IsThe 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 NotThe MVC pattern is very abstract. It is not simply a front end to a data source. AnalogyThe 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). ProblemDifferent views of the same data are a common need. Conversely, the same client needs access to different models. ResponsibilityThe 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 ActivityThe 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. ContextAn application is expected to support varying client and business logic tiers. Motivation or ForcesThe following forces or motivations are the most common reasons designers use this pattern:
ApplicabilityAlthough 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. SolutionWhat can this pattern accomplish? The MVC pattern's solution consists of the following parts:
ConsequencesUsing the MVC pattern has the following consequences:
Known UsesJava 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 PatternsMVC is a very high-level and abstract pattern compared to other patterns, so it has few related patterns. ReferencesFor more information on the MVC pattern, consult the following site: http://java.sun.com/blueprints/patterns/MVC.html Front ControllerThe 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. IsThe 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 NotThe 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. AnalogyThe 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. ProblemWhen 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. ResponsibilityThe 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 ActivityThe Front Controller pattern matches the correct resource to the request. ContextSimplified 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 ForcesThe following forces are the primary reasons for using this pattern:
ApplicabilityDatabases and Web sites especially benefit from a Front Controller. SolutionThe Front Controller pattern's solution consists of the following parts:
ConsequencesUsing the Front Controller pattern has the following consequences:
Known UsesThe Front Controller pattern has the following uses:
Related PatternsThe following patterns are related to the Front Controller pattern:
ReferencesFor more information on the Front Controller pattern, consult the following site: http://java.sun.com/blueprints/corej2eepatterns/Patterns/FrontController.html |