Web Interactive Revolution-the design patterns used in the JSF framework Introduction __ Framework

Source: Internet
Author: User
Design patterns can help users abstract details at a higher level and better understand the architecture. If you are familiar with the GoF design pattern and the JavaServer Faces (JSF) framework, this article can help you gain insight into the design patterns used in the JSF framework and understand how they work.

This article explores the design patterns used in the JSF framework. The design patterns discussed in detail include Singleton, Model-view-controller, Factory method, state, composite, decorator, strategy, Template methods, and Observer mode.

Design Patterns and JavaServer Faces (JSF) technology

Start with a brief introduction to the schema and JSF framework.
mode. Design patterns are a universally applicable method of abstracting problems and solutions. Because schemas are recognized by all developers and architects, schemas can save time and resources. In the case of layman's terms, the pattern is a proven solution to a well-known problem. Patterns can be reused, and reuse makes the solution more robust.
Java Server Faces. The JSF architecture is a WEB application framework. It is driven by the Java Community Process (JCP) and is expected to be a standard framework for WEB application development. There are more than 50 frameworks currently used to develop WEB applications, which illustrates the urgent need to standardize the framework, which is the goal of the JSF framework. deep analysis of JSF patterns

Now let's talk about the various design patterns in the JSF architecture. This article discusses in detail Singleton, Model-view-controller, Factory method, state, composite, decorator, strategy, Template method, and Observer design pattern. I will analyze the purpose of each pattern and its role in the JSF framework.

Singleton mode

The purpose of the Singleton mode is to ensure that only one instance of a class is loaded, and that the instance provides a global access point. When you start a Web application with JSF support, the Web container initializes a Facesservlet instance. At this stage, Facesservlet instantiates application and lifecycle instances for each WEB application. These instances take a well-known Singleton pattern, and usually require only one instance of that type.

A WEB application that uses JSF requires only one instance of the application and lifecycle classes. Lifecycle manages the entire lifetime of multiple JSF requests. Because its state and behavior are shared among all requests, these objects are justified by using the Singleton pattern. The Phaselisteners of lifecycle maintenance is also Singleton mode. Phaselisteners is shared by all JSF requests. The Singleton pattern can be widely used in the JSF framework to reduce memory footprint and provide global access to objects. Navigationhandler (used to determine the logical result of the request) and Viewhandler (used to create the view) is also an example of using the Singleton pattern.

Model-view-controller (MVC)

The purpose of the MVC pattern is to separate the data (that is, model) from the data Representation (View). If your application has multiple representations, you can reuse the controller and model code only by replacing the view layer. Similarly, if you need to change the model, you can largely do without changing the view layer. The controller handles user actions, and user actions can cause model changes and view updates. When a user requests a JSF page, the request is sent to Facesservlet. Facesservlet is the front-end controller servlet used by JSF. Like many other Web application frameworks, JSF uses the MVS pattern to eliminate coupling between views and models. To centralize processing of user requests, the controller servlet changes the model and navigates the user to the view.

Facesservlet is the controller element that all user requests will pass through in the JSF framework. Facesservlet analyzes user requests and invokes various actions on the model using managed beans. Background (backing) or managed (managed) beans are examples of this model. The JSF user interface (UI) component is an example of a view layer. The MVC pattern breaks down tasks to developers with different skills so that the tasks can be performed concurrently so that the GUI designer can create JSF pages with rich UI components, while back-end developers can create managed beans to write specialized business logic code.

Factory method Mode

The purpose of the Factory method pattern is to define an interface for creating objects, but to defer object instantiation to subclasses. In the JSF architecture, the Factory method pattern is used to create objects. Lifecyclefactory is a factory object that creates and returns a lifecycle instance. The Getlifecycle (String Lifecycleid) method of the lifecyclefactory takes the Factory mode pattern, creates (if necessary) according to Lifecycleid, and returns the lifecycle instance. A custom JSF implementation can redefine a getlifecycle abstract method to create a custom lifecycle instance. The default JSF implementation provides the default lifecycle instance. In addition, for each JSF request, Facesservlet gets facescontext from Facescontextfactory. Facescontextfactory is an abstract class that exposes a getfacescontext API,JSF implementation that provides a concrete implementation of the Facescontextfactory and Getfacescontext APIs. This is another example using the Factory method pattern, where the specific facescontextfactory implementation creates the Facescontext object.

State mode

The purpose of the state pattern is to assign states-related logic between different classes that represent states. Facesservlet invokes the Execute and render methods on the Lifcycle instance. Lifecycle coordinates different Phrase to perform JSF requests. Here the JSF implementation follows the state pattern. If this pattern is not used, the lifecycle implementation is messed up by a large number of conditions (that is, "if" statements). The JSF implementation creates a separate class for each state (or phase) and calls the step. Phase is an abstract class that set the public interface for each step. Six phrase (that is, step) are defined in the JSF framework: Restoreviewphase, Applyrequestvalues, Processvalidationsphase, Updatemodelvaluesphase, Invokeapplicationphase and Renderresponsephase.

In state mode, lifecycle passes the Facescontext object to the phase. Each phase or state changes the context information that is passed to it, and then sets the flags in the facescontext itself to indicate the next possible step. The JSF implementation changes its behavior in each step. Each phase can be the cause of the next phase. Facescontext has two kinds of flags renderresponse and Responsecomplete can change the order of execution. After each step has been completed, lifecycle checks to see if these flags were set in the previous stage. If Responsecomplete,lifecycle is set, the execution of the request is completely discarded. If you set the Renderresponse flag after a certain stage, JSF skips over the remaining stages and goes directly to the Render Response phase. If neither of these flags is set, lifecycle continues the next step in order.

Composite Mode

Composite mode allows client code to uniformly process composite objects and base objects. A composite object is a container for the base object. In the first phase (the Restore View phase) and the final phase (Render Response phase), the UI View is constructed using the JSF UI components. Uicomponentbase is an example of a Component abstract class in the composite pattern. Uiviewroot is the composite class, and uioutput (for example) is the leaf (or basic Class). The Uicomponentbase class defines common methods for leaves and composite objects, such as encoding/decoding values and child node management functions. A child node management function, such as GetChildren, returns an empty list for a leaf node and returns its child nodes for a composite node.

Decorator mode

The purpose of the decorator mode is to not dynamically extend an object's behavior through subclasses. The JSF framework has many extension points (you can insert mechanisms). The JSF implementation can use the decorator mode to replace the default Propertyresolver, Variableresolver, ActionListener, Navigationhandler, Viewhandler, or Statemanager. Typically, a custom implementation accepts a reference to the default implementation passed to it through the constructor. A custom implementation simply overwrites a subset of the functionality and delegates other features to the default implementation. If you want to implement a custom Viewhandler, rewrite the Calculatelocale method of the default Viewhandler implementation, you can write the Customviewhandler class as in Listing 1:

Listing 1. Customviewhandler Fragment






Private Viewhandler Oldviewhandler









Strategy mode

The purpose of the strategy model is to encapsulate different concepts. The JSF framework uses the strategy model to render UI components using the delegate implementation model. JSF technology supports two rendering models. In the direct implementation model, the UI component decodes the data in the received request, and then encodes the data to display it. In the delegate implementation model, the decoding and encoding operations are delegated to and build the associated specialized renderer. The latter model utilizes the strategy design pattern, which is more flexible than the direct implementation. In strategy mode, different algorithms are encapsulated in separate objects so that the algorithm can be changed dynamically. The JSF implementation can register additional renderer with an existing Renderkit instance, and when the application is started, the JSF implementation reads the configuration file to link these renderer and UI components together.

Template method Mode

The purpose of the Template method pattern is to defer the changing steps to subclasses, and to define those fixed algorithm steps in the parent class. The JSF framework demonstrates the functionality provided by the Template method pattern through phraselisteners. Using Template method (or "hook") enables WEB authors to provide implementations for optional steps between different stages, while the main phase remains consistent with the JSF framework definition. The JSF framework provides phaselisteners, conceptually similar to the variable steps in Template method mode. The JSF framework has six predefined phases, between which WEB authors can implement phaselisteners to provide hooks similar to the Template method hook. In fact, this structure is more extensible than the Template method pattern. Hooks can be provided after each stage by registering the Phraseid for Any_phrase Phaselistener. If Phaseid is the ANY_PHASE,JSF implementation, the Phaselistener is invoked before and after each phase. Implementations in the JSF framework are slightly different because there can be no phaselistener at all, but in Template method, subclasses often redefine the variable steps of abstraction in the parent class.

Observer mode

The purpose of the Observer mode is to automatically notify all dependent objects (that is, observers) when the state of the target object changes. JSF implements the Observer pattern in the UI component. JSF has two types of built-in events: ActionEvent and Valuechangedevent. ActionEvent is used to determine the activation of user interface components, such as buttons. The JSF implementation notification is added to one or more action listeners on the button when the user clicks the button. The button is activated, or the State of the button (subject) changes. All listeners added to the button (that is, the observer) are notified that the body state has changed. Similarly, the JSF implementation notifies the Valuechangelistener when the value in the input UI component changes.

   Concluding remarks

The JSF framework leverages Singleton, Model-view-controller, Factory method, state, composite, decorator, strategy, Template method, and Observer design pattern. Because its architecture is based on validated design patterns, this is a robust framework in which patterns are well utilized in the JSF framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.