Context Object Design Pattern in Java

We can use a Context Object to encapsulate state in a protocol-independent way to be shared throughout your application. Context object pattern encapsulating system data in a Context Object allows it to be shared with other parts of the application without coupling the application to a specific protocol.
For example, an HTTP request parameter exists for each field of an HTML form and a Context Object can store this data in a protocol-independent manner while facilitating its conversion and validation. Then other parts of the application simply access the information in the Context Object, without any knowledge of the HTTP protocol. Any changes in the protocol are handled by the Context Object, and no other parts of the application need to change. A Context Object’s main goal is to share system information in a protocol- independent way, improving the reusability and maintainability of an application.

Real world examples

Below Context Objects are examples of this pattern
  • ApplicationContext is the central interface within a Spring application for providing configuration information to the application.
  • SecurityContext is used to store the details of the currently authenticated user and which can further be accessed through the application.
  • ServletContext is used to share configuration information with all the servlets.
Let's see how this pattern share system information in a protocol- independent way, improves the reusability and maintainability of an application.

This pattern is divided into a number of sections for simplicity like the problem, forces, solution, structure, implementation, applicability etc.
Table of contents
Problem
Forces
Solution
Explanation
Structure - Class Diagram, Sequence Diagram
Participants and Responsibilities
Implementation
Consequences
Applicability
Real world examples
References

Problem

(Problem section describes the design issues faced by the developer)
You want to avoid using protocol-specific system information outside of its relevant context.

Forces

  • You have components and services that need access to system information.
  • You want to decouple application components and services from the protocol specifics of system information.
  • You want to expose only the relevant APIs within a context.

Solution

Use a Context Object to encapsulate state in a protocol-independent way to be shared throughout your application.

Structure

Class Diagram


Sequence Diagram

Participants and Responsibilities

Client uses a ContextFactory to create a ContextObject using a ProtocolInterface. The ContextObject shields the surrounding application components and services from the underlying details of the ProtocolInterface.
Client : Creates an object with ProtocolInterface.
ProtocolInterface : An object that exposes protocol or tier-specific details.
ContextFactory : A ContextFactory creates a protocol- and tier-independent
ContextObject : ContextObject ContextObject is a generic object used to share domain-neutral state throughout an application.

Implementation

There are numerous strategies to implement a Context Object, so these strategies are grouped based on the type of Context Object being created. When a ContextObject encapsulates request state, it is also referred to as a RequestContext.
In the below example,HttpServletRequest is a protocol-specific Request object and should have limited exposure within an application.

The ContextFactory creates a RequestContext(ContextObject and transfers state into it from the HttpServletRequest. The data in the RequestContext typically goes through an initial form-level validation at this point; for example, a check for empty fields or a check for a credit card number having the correct number of digits.

As business processing is performed, the ContextObject state will typically go through the second round of validation that is business-related, such as whether a value is within an appropriate range. The relevant request state is transferred into a standard Map implementation, which is passed around.
public class FrontController extends HttpServlet {
    ...
    private void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException,
        java.io.IOException {

            // create RequestContext object using Map Strategy
            Map requestContextMap = new HashMap(request.getParameterMap());
            Dispatcher dispatcher = new Dispatcher(request, response);
            requestContextMap.put("dispatcher", dispatcher);

            // Create ApplicationController instance
            ApplicationController applicationController =
                new ApplicationControllerImpl();

            // Request processing
            ResponseContext responseContext =
                applicationController.handleRequest(requestContextMap);

            // Response processing
            applicationController.handleResponse(requestContextMap,
                responseContext);
        }
        ...
}

Applicability

In layered Architecture, if we want to share system information across different System layers then use this design pattern

References

Related Presentation Tier Posts

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments