Revolution in web interaction-design patterns used in the JSF framework

Source: Internet
Author: User
The design pattern can help users abstract details at a higher level and better understand the architecture. If you are familiar with the gof design patterns and the JavaServer faces (JSF) framework, this article will help you gain insight into the design patterns used in the JSF framework and gain an in-depth understanding of its working principles.

This article discusses 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 method, and observer mode.

Design Pattern and JavaServer faces (JSF) Technology

First, we will briefly introduce the mode and JSF framework.

  • Mode.The design pattern is a universally applicable method that abstracts problems and solutions. Because the pattern is recognized by all developers and architects, it can save time and resources. In other words, a pattern is a proven solution to a problem that someone knows. The mode can be reused to make the solution more robust.
  • Java Server faces.The JSF architecture is a Web application framework. It is promoted by Java Community process (JCP) and is expected to become a standard framework for Web application development. At present, there are more than 50 frameworks used to develop Web applications. This shows that Framework standardization is urgently required. This is exactly the goal of the JSF framework!

In-depth analysis of the JSF Mode

Now we will discuss the various design patterns in the JSF architecture. This article will discuss in detail Singleton, Model-View-controller, factory method, state, composite, decorator, strategy, template method, and observer design patterns. I will analyze the usage of each mode and its role in the JSF framework.

Singleton Mode

The Singleton mode ensures that only one instance of the class is loaded and the instance provides a global access point. When a web application with JSF support is started, the Web Container initializes a facesservlet instance. In this phase, facesservlet instantiates the application and lifecycle instances for each web application once. These instances use the well-known Singleton mode. Generally, only one instance of this type is required.

A Web application using JSF only needs an instance of the application and lifecycle classes. Lifecycle manages the entire life cycle of multiple JSF requests. Because its status and behavior are shared among all requests, these objects adopt the singleton mode reasonably. The phaselisteners maintained by lifecycle is also in singleton mode. Phaselisteners is shared by all JSF requests. The Singleton mode can be widely used in the JSF framework to reduce memory usage and provide global access to objects. Navigationhandler (used to determine the logic result of the request) and viewhandler (used to create a view) are also examples of using the singleton mode.

Model-View-controller (MVC)

The purpose of the MVC mode is to separate the data (model) from the data view. If the application has multiple representations, you can replace the view layer and reuse the controller and model code. Similarly, if you need to change the model, you can not change the view layer to a large extent. The controller processes user actions. User Actions may cause model changes and view updates. When a user requests a JSF page, the request is sent to facesservlet. Facesservlet is a front-end controller Servlet used by JSF. Like many other web application frameworks, JSF uses the MVS mode to eliminate coupling between views and models. To centrally process user requests, the Controller servlet changes the model and directs the user to the view.

Facesservlet is the Controller element for all user requests in the JSF framework. Facesservlet analyzes user requests and uses managed beans to call various actions on the model. Backing or managed bean is an example of this model. The JSF User Interface (UI) component is an example of the view layer. The MVC mode splits tasks into developers with different skills so that these tasks can be performed at the same time, so that Gui designers can use a wide range of UI components to create JSF pages, at the same time, backend developers can create managed beans to write specialized business logic code.

Factory method mode

The purpose of the factory method mode is to define an interface for creating objects, but to postpone Object Instantiation to subclass. In the JSF architecture, the factory method mode is used to create objects. Lifecyclefactory is a factory object for creating and returning lifecycle instances. The getlifecycle (string lifecycleid) method of lifecyclefactory adopts the factory method mode. It is created based on lifecycleid (if needed) and returns the lifecycle instance. The custom JSF implementation can redefine the 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 obtains facescontext from facescontextfactory. Facescontextfactory is an abstract class that exposes the getfacescontext API. The JSF implementation provides the specific implementation of facescontextfactory and getfacescontext APIs. This is another example of using the factory method mode. The specific facescontextfactory implementation creates a facescontext object.

State Mode

The State mode aims to allocate state-related logic between different classes that indicate the state. Facesservlet calls the execute and render methods on the lifcycle instance. Lifecycle coordinates different phrase to execute JSF requests. Here, the JSF implementation follows the state mode. If this mode is not used, the lifecycle implementation will be confused by a large number of conditions (that is, the "if" Statement. The JSF implementation creates a separate class for each State (or stage) and calls step. Phase is an abstract class that defines the public interfaces of each step. Six phrase (STEP) are defined in the JSF framework: restoreviewphase, applyrequestvalues, processvalidationsphase, updatemodelvaluesphase, invokeapplicationphase, and renderresponsephase.

In State mode, lifecycle passes the facescontext object to phase. The context information transmitted to each stage or state change, and then the flag in the facescontext itself indicates the next possible step. The JSF Implementation changes its behavior in each step. Each stage can be used as the cause of the next stage. Facescontext indicates that renderresponse and responsecomplete can change the execution sequence. After each step is completed, lifecycle checks whether these flags are set in the previous stage. If responsecomplete and lifecycle are set, the request execution is completely abandoned. If the renderresponse flag is set after a stage, JSF skips the remaining stage and directly enters the render response stage. If neither of the two flags is set, the lifecycle proceeds to the next step in order.

Composite Mode

The composite mode enables the customer code to process composite objects and basic objects in a unified manner. A composite object is the container of a basic object. In the restore view phase and the render response phase, the UI view is constructed using the jsf ui component. Uicomponentbase is an example of the component abstract class in composite mode. Uiviewroot is a composite class, And uioutput (for example) is a leaf (or basic class ). The uicomponentbase class defines public methods for leaf and composite objects, such as encoding/decoding values and subnode management functions. Subnode management functions, such as getchildren, return an empty list for leaf nodes and subnodes for composite nodes.

Decorator Mode

The purpose of the decorator mode is to dynamically expand the behavior of objects without subclass. The JSF framework has many extensions (the plug-in mechanism ). The default propertyresolver, variableresolver, actionlistener, navigationhandler, viewhandler, or statemanager can be replaced by the decorator mode in JSF implementation. Generally, custom implementations are referenced by the default implementation passed to the constructor. Custom implementations only rewrite a subset of functions, and delegate other functions to default implementations. If you want to implement custom viewhandler and rewrite the calculatelocale method implemented by default viewhandler, you can write it as in Listing 1.Customviewhandler class:

Listing 1. mviewhandler snippet

 
public class CustomViewHandler extends ViewHandler {
public CustomViewHandler(ViewHandler handler) {
super();
oldViewHandler = handler;
}
private ViewHandler oldViewHandler = null;
public void renderView (facesContext context, UIViewRoot view) {
//delegate method to oldViewHandler
oldViewHandler.renderView(context, view);
}
//custom implementation of calculateLocale
public Locale calculateLocale(FacesContext context) {
}
}

Strategy Mode

The goal of the Strategy Mode is to encapsulate different concepts. The JSF framework uses the Strategy Mode to implement model rendering UI components using delegation. 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 for display. In the delegate implementation model, decoding and encoding operations are delegated to a dedicated Renderer associated with the formation. The latter model utilizes the strategy design pattern, which is more flexible than direct implementation. In the Strategy Mode, different algorithms are encapsulated in individual objects, so that the algorithms can be dynamically changed. The JSF implementation can register another Renderer with an existing renderkit instance. When an application is started, the JSF implementation reads the configuration file and associates the Renderer with the UI component.

Template Method Mode

The purpose of the template method mode is to postpone the changed steps to the subclass, and define fixed algorithm steps in the parent class. The JSF framework uses phraselisteners to demonstrate the functions provided by the template method mode. The template method (or "Hook") enables the Web author to provide implementation for optional steps between different stages, while the main stages are still consistent with the definition of the JSF framework. The JSF framework provides phaselisteners, Which is conceptually similar to the variable steps in the template method mode. The JSF framework has six predefined stages. In each phase, web authors can implement phaselisteners to provide hooks similar to template method hooks. In fact, this structure is more extensible than the template method mode. You can provide hooks after each phase by registering a phaselistener with phraseid any_phrase. If the phaseid is any_phase, The JSF implementation calls the phaselistener before and after each stage. The implementation in the JSF framework is slightly different because phaselistener is not available at all. However, in the template method mode, subclasses usually redefine the abstract Variable Steps in the parent class.

Observer Mode

The purpose of the observer mode is to automatically notify all dependent objects (that is, the observer) when the status of the target object changes ). JSF implements the observer mode in the UI component. JSF has two built-in events: actionevent and valuechangedevent. Actionevent is used to determine the activation of user interface components (such as buttons. When you click a button, one or more action listening programs added to the JSF implementation notification button. The button is activated, or the status of the button (subject) changes. All listeners (namely the observer) added to the button are notified that the status of the subject has changed. Similarly, when the value in the input UI component changes, the JSF implementation notifies valuechangelistener.

  Conclusion

The JSF framework uses Singleton, Model-View-controller, factory method, state, composite, decorator, strategy, template method, and observer design patterns. Because its architecture is built on a verified design pattern, it is a robust framework that is 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.