50% found this document useful (2 votes)
2K views

Design Patterns: Exam Objectives

The document discusses several Java EE design patterns including Service Starter, Singleton, Bean Locator, Resource Binder, Dependency Injection, Payload Extractor, Context Holder, and Thread Tracker. It provides descriptions of each pattern, explaining what problems they address and how they can be implemented. It also discusses design patterns like Facade, Strategy, Observer, Composite, and Abstract Factory and how they relate to specific scenarios.

Uploaded by

eng_bahi
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
50% found this document useful (2 votes)
2K views

Design Patterns: Exam Objectives

The document discusses several Java EE design patterns including Service Starter, Singleton, Bean Locator, Resource Binder, Dependency Injection, Payload Extractor, Context Holder, and Thread Tracker. It provides descriptions of each pattern, explaining what problems they address and how they can be implemented. It also discusses design patterns like Facade, Strategy, Observer, Composite, and Abstract Factory and how they relate to specific scenarios.

Uploaded by

eng_bahi
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Design Patterns

Exam Objectives
Demonstrate knowledge of Java EE design patterns including: Service Starter, Singleton, Bean Locator, Resource Binder, Dependency Injection, Payload Extractor, Context Holder, and Thread Tracker. Select an appropriate pattern for a given application challenge from the following: Facade, Strategy, Observer, Composite, and Abstract Factory. Identify a design pattern, using a description of its features, from the following: Facade, Strategy, Observer, Composite, and Abstract Factory. Identify the use of the law of leaky abstractions or a specific anti-pattern in a given scenario. Select the appropriate pattern for a given scenario from the following Web Services patterns: Web Service Cache, Web Service Broker, Asynchronous Interactions, and JMS bridge.

Java EE design Patterns


Service Starter You need to perform initialization work at the application servers or applications start time. The Service Starter pattern invokes existing Controls or Boundaries to enforce their initialization. It is not related to other patterns regarding its responsibility. The singleton pattern, however, is structurally identical to the Service Starter pattern. From a technical perspective, a singleton is closely related to all patterns that rely on the @Singleton functionality such as Service Starter (Java EE), Re-Injector, Configurator, Transparent Cache Integrator, and Scheduler. Java EE 6 Singleton Session Bean is the best option for Service Starter pattern. Bean Locator pattern DI can be considered to be Bean Locator 2.0. DI uses a generic version of Bean Locator factored out from the application code into the framework. Such a generic Bean Locator is configured with metadata derived from conventions, class files, annotations, and, optionally, XML. The located bean is automatically injected by the framework. Note that the J2EE ServiceLocator is also closely related to BeanLocator. Its implementation was some what limited because of the lack of global JNDI names, generics, and annotations. EJB 3.1 introduced application server- independent, global JNDI naming for EJB components. The JNDI names have the following syntax: java:global[/ < app-name >]/ < module-name 4 <

bean-name ># < fully-qualified-interface-name >. The app-name and fully-qualified-interfacename are optional. Neither the use of the JNDI API itself nor the construction of the JNDI names is convenient. The encapsulation of both in a utility class (BeanLocator) makes the lookup not only more convenient, but it also reduces potential errors and decouples the application from the JNDI details. Forces Domain and infrastructural JNDI code needs to be separated. The global JNDI name should be constructed conveniently by minimizing potential errors. BeanLocator should be responsible for the global JNDI name construction, as well as for performing the actual JNDI lookup with eventual casting to the expected type. Resource Binder Bind a custom resource into JNDI using a @Singleton with @Startup and the JNDI API (Context.(re)bind()). Note that application servers proprietary JNDI implimentation may enforce some restrictions on the resource object (such as serializability). Dependency Injection Extender pattern The problem: You need to use some kind of Dependency Injection (DI for short) to provision some System Under Test (SUT for short) in tests you are writing, but can not or do not want to use a DI framework to do so. Of course, the simplest form of DI is simply passing things to a constructor. But you probably do not want to code every class to be handed every dependency at construction. And you definitely do not want to expose the private implementation through some unnecessary interface. The solution: Dependency Injection by Extension pattern. How it works: We need to provide DI helper s as protected methods in our SUT and subclass it from within test case as script-level class, to expose the DI helpers as public and/or use constructor to do some of the DI work allowing us to inject mocked dependencies for our test.

Payload Extractor pattern


The Message Driven Bean method onMessage expects the interface javax.jms.Message as a parameter that has to be cast into a more concrete representation to extract the payload. The method onMessage is transactional. Messages are considered delivered only if the transaction is going to be committed without any unhandled, unchecked exceptions. From an implementation point of view, the PayloadExtractor is similar to ThreadTracker or any other aspect. PayloadExtractor forwards the content of the message to Controls, which are injected to the MessageDrivenBean instances.

The extraction of the payload requires you to check the message type, cast it, extract the payload, potentially cast it again (for example, casting the ObjectMessage payload from Serializable to something more meaningful), and catch and properly handle checked exceptions. These tasks are repetitive, verbose, and error-prone. Especially hard to implement is proper handling of wrong message types. All destination instances are identical-they are distinguished only by their names, not by the message type. Nothing prevents other producers from sending messages with unexpected types. Such unexpected messages can cause ClassCastExceptions, which leads to the rollback of the current transaction. As a result, the message would be delivered again. The number of attempts depends on the message providers configuration. Ignoring unwanted messages is not a good strategy either; the messages will disappear from the destination and with them will disappear the chance to find the actual configuration error. Syntactically incorrect messages or messages with wrong types are often called poisoned messages. Poisoned messages have to be handled properly. At the very least, they have to be redirected into a dedicated dead-letter queue. The type checking and error handling is reusable and has to be factored out from the actual processing logic. PayloadExtractor should streamline the MessageDrivenBean implementation. Solution An interceptor is an obvious candidate for the realization of cross-cutting concerns such as errorhandling and payload extraction. The method MessageDrivenBeans# onMessage can be entirely wrapped by an interceptor.

Context Holder pattern


The application server is managing concurrency and threads for you. The invocation context, such as transaction and security information, is associated with the current execution thread by the EJB container. Context Holder is used by Boundaries and their interceptors to pass data to services and DAOs down the chain. The ThreadLocal strategy can even be applied in a web container to pass contextual information from the UI layer back to the service components. Because the Context Holder uses interceptors as well, it is similar, to the Aspect, Thread Tracker, and Payload Extractor patterns. The combination of the Context Holder and the Re-Injector patterns allows seamless integration of context data to all managed beans.

Thread Tracker pattern


Session bean instances are always executed by exactly one thread. For each method execution, a single thread is associated with the bean instance and, in most cases, even with the entire call tree. The application server pools the threads and reuses them for incoming requests. The threads have arbitrary, application server specific names and are often numbered, for example, _ejb-thread-pooll, and _ejb-thread-pool2 for @Asynchronous method calls and httpSSLWorkerThread-8080-1, httpSSLWorkerThread-8080-2, and so on for synchronous requests in the case of GlassFish v3. ThreadTracker is applied on synchronous and asynchronous boundarie for finer monitoring and searching for hotspots. The most useful place is ThreadTracker for message-driven beans and @Asynchronous methods monitoring. Because the threads are pooled and have generic names, it is hard to associate a problematic method in a deadlock scenario with a stuck thread. For troubleshooting purposes, it is helpful to name the threads after the performed method for the duration of its execution and roll back this change just after the method call. The solution should be portable across servers. The extension of the monitoring capabilities should be clearly separated from the business code. The thread tracking should be easily activated and deactivated. It should be easy to remove all additional monitoring functionality (and class files as well) before production deployment. The thread tracking should be generic enough to be applied to existing beans. Although the solution is portable it clearly violates the spec. Therefore, ThreadTracker should be used only for debugging purposes. The business methods of the bean are executed by pooled threads with generic names. The challenge is to change the thread name to the bean name concatenated with the method name, and robustly reset the change after each call. You will have to intercept the call before the actual method execution. This is a perfect task for an interceptor. It is executed in the same transaction, thread, and security context as the managed bean, and it even has access to the bean instance. An interceptor wraps the bean instance and is a perfect place for changing the name of the thread:

Java EE design Patterns


Intercepting Filter (Pre / Post Processing mechanism) Used to create pluggable filters to process common services in a standard manner without requiring changes to core request processing code. The filters intercept incoming requests and outgoing responses, allowing preprocessing and post-processing. We are able to add and remove these filters unobtrusively, without requiring changes to our existing code. Used to create pluggable filters to process common services in a standard manner without requiring changes to core request processing code. The filters intercept incoming requests and outgoing responses, allowing pre-processing and post-processing. We are able to add and remove these filters unobtrusively without requiring changes to our existing code. Java EE design Patterns

Composite View (Defines structure of the display with sub-views)


Use composite views that are composed of multiple atomic sub views. Each component of the template may be included dynamically into the whole and the layout of the page may be managed independently of the content. View Helper (Business Data Adapter) A view contains formatting code, delegating its processing responsibilities to its helper classes, implemented as JavaBeans or custom tags. Helpers also store the view's intermediate data model and serve as business data adapters.

Dispatcher View (View management) Combine a controller and dispatcher with views and helpers to handle client requests and prepare a dynamic presentation as the response. Controllers do not delegate content retrieval to helpers, because these activities are deferred to the time of view processing. A dispatcher is responsible for view management and navigation and can be encapsulated either within a controller, a view, or a separate component. Java EE Design Patterns Service to Worker (View management and navigation) Combine a controller and dispatcher with views and helpers to handle client requests and prepare a dynamic presentation as the response. Controllers delegate content retrieval to helpers, which manage the population of the intermediate model for the view. A dispatcher is responsible for view management and navigation and can be encapsulated either within a controller or a separate component. Java EE Design Patterns

Business Delegate (Business Service Adapter) 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 DB architecture. Session Facade (Hides business objects workflow layer) Use a session bean as a facade to encapsulate the complexity of interactions between the business objects participating in a workflow. The Session Facade manages the business objects, and provides a uniform coarse-grained service access layer to clients.

Service Locator (Caches JNDI objects) Use a Service Locator object to abstract all JNDI usage and to hide the complexities of initial context creation, EJB home object lookup, and EJB object re-creation. Multiple clients can reuse the Service Locator object to reduce code complexity, provide a single point of control, and improve performance by providing a caching facility. Value List Handler (Search Result service to the clients requirements) Use a Value List Handler to control the search, cache the results, and provide the results to the client in a result set whose size and traversal meets the client's requirements. Composite Entity (Manages database table relationships) Use Composite Entity to model, represent, and manage a set of interrelated persistent objects rather than representing them as individual fine-grained entity beans. A Composite Entity bean represents a graph of objects.

Front Controller (Central point of access for all requests) 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.

Transfer Object (Used to transfer the enterprise data in between the tiers) Use a Transfer Object to encapsulate the business data. A single method call is used to send and retrieve the Transfer Object. When the client requests the enterprise bean for the business data, the enterprise bean can construct the Transfer Object, populate it with its attribute values, and pass it by value to the client. Service Activator (Asynchronous Processor) Use a Service Activator to receive asynchronous client requests and messages. On receiving a message, the Service Activator locates and invokes the necessary business methods on the business service components to fulfill the request asynchronously. Data Access Object (Decouple SQL Logic from business components) Use a Data Access Object (DAD) to abstract and encapsulate all access to the data source. The 0.4.0 manages the connection with the data source to obtain and store data.

GoF Design Patterns


Faade Provide an unified interface to a groups of interfaces in a subsystem and it defines a higherlevel interface that makes the subsystem easier to use. Strategy It defines a group of classes that represent a set of possible behaviors. Observer Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Composite Software component may be an individual object or may represent a collection of objects. Composite pattern is suitable for both cases. In tree classifications, some objects may be nodes with additional branches and some may be leaves. Abstract Factory The pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. Hot potato Anti- Pattern

Hot potato Anti- Pattern


A hot potato is a particular situation where a MDB repeatedly receives a same message and throws an exception while handling the message. When a JMS server does not receive an acknowledgement for a message delivered to a consumer, the server's only recourse is to resend the message. This sets the stage for repeated delivery of the same message indefinitely when the consumer that is processing the message does not handle an exception condition properly.

Web Services Design Patterns


Asynchronous Interaction A client sends a request to a service and waits until the service replies The JMS Bridge The function of the bridge is to consume messages from a source queue or topic, and send them to a target queue or topic, typically on a different server. The source and target servers do not have to be in the same cluster which makes bridging suitable for reliably sending messages from one cluster to another, for instance across a WAN, and where the connection may be unreliable.

Web Service Broker A Web Service Broker to expose and broker one or more services using XML and web protocols. Strategies Custom XML Messaging Strategy Java Binder Strategy Web Service Cache Despite advancements in network and processor speeds, performance remains a key concern among application developers. So whether you are writing an XML Web service, pushing image bitmaps to a video card, or even engineering that next great processing chip, you will invariably want to consider utilizing a universal mechanism for improving performance: a cache. Application Caching HTTP Caching Performing application caching on the server, caching responses on the client, or simply designing options in your XML Web service so that smart clients can offload some of the fundamental processing work from your server.

You might also like