SlideShare utilise les cookies pour améliorer les fonctionnalités et les performances, et également pour vous montrer des publicités pertinentes. Si vous continuez à naviguer sur ce site, vous acceptez l’utilisation de cookies. Consultez nos Conditions d’utilisation et notre Politique de confidentialité.
SlideShare utilise les cookies pour améliorer les fonctionnalités et les performances, et également pour vous montrer des publicités pertinentes. Si vous continuez à naviguer sur ce site, vous acceptez l’utilisation de cookies. Consultez notre Politique de confidentialité et nos Conditions d’utilisation pour en savoir plus.
Design Patterns• A pattern is a proven solution to a problem in acontext.• Christopher Alexander says each pattern is athree-part rule which expresses a relationbetween a certain context, a problem, and asolution.• Design patterns represent a solutions toproblems that arise when developing softwarewithin a particular context.i.e Patterns = problems.solution pairs in a context
Categorizing PatternPatterns, then, represent expert solutions torecurring problems in a context and thus havebeen captured at many levels of abstractionand in numerous domains. Numerouscategories are:• Design• Architectural• Analysis• Creational• Structural• Behavioral
MVC Design Pattern• Name (essence of the pattern)– Model View Controller MVC• Context (where does this problem occur)– MVC is an architectural pattern that is used when developinginteractive application such as a shopping cart on the Internet.• Problem (definition of the reoccurring difficulty)– User interfaces change often, especially on the internet where look-and-feel is a competitive issue. Also, the same information ispresented in different ways. The core business logic and data isstable.
MVC Pattern• Solution (how do you solve the problem)– Use the software engineering principle of “separation of concerns” to dividethe application into three areas:• Model encapsulates the core data and functionality• View encapsulates the presentation of the data therecan be many views of the common data• Controller accepts input from the user and makesrequest from the model for the data to produce anew view.
MVC Architecture• The Model represents the structure of the data in theapplication, as well as application-specific operationson those data.• A View (of which there may be many) presents data insome form to a user, in the context of some applicationfunction.• A Controller translates user actions (mouse motions,keystrokes, words spoken, etc.) and user input intoapplication function calls on the model, and selects theappropriate View based on user preferences andModel state.
Intercepting Filter• Context: The presentation-tier request handlingmechanism receives many different types of requests,which require varied types of processing beforeforwarding to handler.• Problem: Preprocessing and post-processing of a clientWeb request and response are required.• Solution: Create pluggable filters to process commonservices in a standard manner without requiringchanges to core request processing code.• The filters intercept incoming requests and outgoingresponses, allowing preprocessing and post-processing.• Such filters can be added or removed unobtrusively,without requiring changes to our existing code.
Intercepting Filter• Used for common services such as security,logging, debugging etc.• These filters are components that areindependent of the main application code.• Filters allow on the fly transformations of payloadand header of both the request into a resourceand the response from a resource.• Filters do not generally create a response orrespond to a request as servlets do , rather theyare used to modify the request or the response
Writing a Filter• Implement the javax.servlet.Filter interface• Container will call the doFilter() method.• The doFilter method will modify the request orresponse and then call the next filter in thefilter chain.• The FilterManager manages filter processing. Itcreates the FilterChain with the appropriatefilters, in the correct order, and initiatesprocessing.• The FilterChain is an ordered collection ofindependent filters.
Front Controller• Context: The presentation-tier request handlingmechanism must control and coordinateprocessing of each user across multiple requests,in either a centralized or decentralized manner.• Problem: The system requires a centralizedaccess point for presentation-tier requesthandling to support the integration of systemservices, content retrieval, view management,and navigation.
Front Controller• Solution: Use a controller as the initial pointof contact for handling a request.• The controller manages the handling of therequest, including invoking security servicessuch as authentication and authorization,delegating business processing, managing thechoice of an appropriate view, handling errors,and managing the selection of contentcreation strategies.
Front Controller• The controller provides a centralized entry pointthat controls and manages Web request handling.• Helps to reduce the code in form of scriptlets inJSP page and promotes code reuse acrossrequests.• The Controller coordinates with a dispatchercomponent for view management and navigation.• An application may use multiple controllers in asystem, each mapping to a set of distinct services.
View Helper• Context: The system creates presentationcontent, which requires processing of dynamicbusiness data.• Problem: Presentation tier changes occuroften and are difficult to develop and maintainwhen business data access logic andpresentation formatting logic are interwoven.• This makes the system less flexible, lessreusable, and generally less resilient to changeand reduces modularity.
View Helper• Solution: A view contains formatting code,delegating its processing responsibilities to itshelper classes, implemented as JavaBeans orcustom tags.• Helpers also store the views intermediate datamodel and serve as business data adapters.• Encapsulating business logic in a helper instead ofa view makes our application more modular andfacilitates component reuse.• The overriding goal is partitioning of businesslogic outside of the view.
Dispatcher View• Context: System controls flow of execution andaccess to presentation processing, which isresponsible for generating dynamic content.• Problem: There is no centralized component formanaging access control, content retrieval or viewmanagement, and there is duplicate control codescattered throughout various views.• Additionally, business logic and presentationformatting logic are intermingled within theseviews, making the system less flexible, lessreusable, less resilient to change and reducingmodularity.
Dispatcher View• Solution: Combine a controller and dispatcherwith views and helpers to handle clientrequests and prepare a dynamic presentationas the response.• Controllers do not delegate content retrievalto helpers, because these activities aredeferred to the time of view processing.• A dispatcher is responsible for viewmanagement and navigation and can beencapsulated either within a controller, a view,or a separate component.
Dispatcher View• Dispatcher pattern and the Service to Workerpattern describe a similar structure.• Unlike the Service to Worker pattern, theDispatcher View pattern suggests deferringcontent retrieval to the time of view processing.• In the Dispatcher View pattern, the dispatchertypically plays a limited to moderate role in viewmanagement.• Dispatcher View describes the combination of theFront Controller and View Helper patterns with adispatcher component.
Dispatcher View• A limited role for the dispatcher occurs when nooutside resources are utilized in order to choosethe view. For example:• http://some.server.com/servlet/Controller?next=login.jsp• The dispatcher playing a moderate role is thecase where the client submits a request directlyto a controller with a query parameter thatdescribes an action to be completed:• http://some.server.com/servlet/Controller?action=login• The dispatcher may access resources such as anXML configuration file that specifies theappropriate view to display.
Service to Worker• Context: The system controls flow of executionand access to business data, from which it createspresentation content.• Problem: There is no centralized component formanaging access control, content retrieval, orview management, and there is duplicate controlcode scattered throughout various views.• Additionally, business logic and presentationformatting logic are intermingled within theeviews, making the system less flexible, lessreusable, and less resilient to change.
Service to Worker• Solution: Combine a controller and dispatcherwith views and helpers to handle client requestsand prepare a dynamic presentation as theresponse.• Controllers delegate content retrieval to helpers,which manage the population of theintermediate model for the view.• A dispatcher is responsible for view managementand navigation and can be encapsulated eitherwithin a controller or a separate component.
Service to Worker• In the Service to Worker pattern, the dispatchertypically plays a moderate to large role in viewmanagement.• In Service to Worker pattern, the dispatcher canbe more sophisticated and may invoke a businessservice to determine the appropriate view todisplay.• The shared structure of Service to Worker andDispatcher View consists of a controller workingwith a dispatcher, views, and helpers.
Business Delegate• Context: A multi-tiered, distributed system requires remote methodinvocations to send and receive data across tiers. Clients areexposed to the complexity of dealing with distributed components.• Problem: Presentation-tier components interact directly withbusiness services, exposing the underlying implementation detailsof the business service API to the presentation tier.• The presentation-tier components are vulnerable to changes inimplementation of the business services.• There is a detrimental impact on network performance becausepresentation-tier components using the business service API maketoo many invocations over the network, with no client-side cachingmechanism or aggregating service.• Exposing the service APIs directly to the client forces the client todeal with the networking issues associated with the distributednature of Enterprise JavaBeans (EJB) technology.
Business Delegate• Solution: Use a Business Delegate to reduce couplingbetween presentation-tier clients and businessservices.• The Business Delegate hides the underlyingimplementation details of the business service, such aslookup and access details of the EJB architecture.• Business Delegate reduces the coupling betweenpresentation-tier clients and the systems businessservices, and other tiers.• The Business Delegate hides underlying service,handles the exceptions from the business services,performs retry or recovery operations on failure.• It can cache results and references to remote businessservices improving the performance.
Session Facade• Context: Enterprise beans encapsulate business logicand business data and expose their interfaces, and thusthe complexity of the distributed services, to the clienttier.• Problem:• Tight coupling, which leads to direct dependencebetween clients and business objects;• Too many method invocations between client andserver, leading to network performance problems;• Lack of a uniform client access strategy, exposingbusiness objects to misuse.
Session Facade: The Problem• The client must represent and implement thecomplex interactions regarding businessobject lookups and creations.• The client grows larger and more complex tofulfill increasing requirements.• The client becomes very susceptible tochanges in the business object layer;• The client is unnecessarily exposed to theunderlying complexity of the system.
Session Facade• Solution: Use a session bean as a facade toencapsulate the complexity of interactionsbetween the business objects participating in aworkflow.• The Session Facade manages the businessobjects, and provides a uniform coarse-grainedservice access layer to clients.• The Session Facade manages the interactionsbetween the business data and business serviceobjects participating in the workflow, and itencapsulates the business logic associated withthe requirements.
Session Facade• The session bean (representing the SessionFacade) manages the relationships betweenbusiness objects.• The session bean also manages the life cycle ofthese participants by creating, locating (lookingup), modifying, and deleting them as required bythe workflow.• Some relationships between business objects aretransient, which means that the relationship isapplicable to only that interaction or scenario,while other relationships may be morepermanent.
Service Locator• Context: Service lookup and creation involvescomplex interfaces and network operations.• Problem: The J2EE clients must either locate theservice component or create a new component inorder to interact with the service componentssuch as EJB and JMS.• The JNDI API enables clients to obtain an initialcontext object that holds the component name toobject bindings and is valid for the client session.• Since locating a JNDI-administered service objectis common to all clients that need to access thatservice object, the JNDI code is duplicated.• Also the JNDI code is dependent on the vendorsupplied context factory implementation.
Service Locator• Solution: Use a Service Locator object to abstractall JNDI usage and to hide the complexities ofinitial context creation, EJB home object lookup,and EJB object re-creation.• Multiple clients can reuse the Service Locatorobject to reduce code complexity, provide asingle point of control, and improve performanceby providing a caching facility.• The pattern provides a mechanism to abstract alldependencies and network details into theService Locator.
Transfer Object Assembler• Context: The server-side business components areimplemented using session beans, entity beans, DAOsetc.• Application clients frequently need to access data thatis composed from multiple objects.• Problem: Application clients typically require the datafor the model or parts of the model to present to theuser or to use for an intermediate processing stepbefore providing some service.• The model is a distributed collection of objects such asDAO, session beans etc put together in a structuredmanner.• The client obtains the model by access individuallyeach distributed object that defines the model.
Transfer Object Assembler• A tight coupling between the client and thedistributed components of the model over thenetwork.• Client accesses the numerous distributedcomponents degrading the perfroamnce.• The client must reconstruct the model afterobtaining the models parts from the distributedcomponents.• Changes to the model require changes to theclient as client tightly coupled to the model.
Transfer Object Assembler• Solution: Use a Transfer Object Assembler to build therequired model or sub-model.• The Transfer Object Assembler uses Transfer Objects toretrieve data from various business objects and otherobjects that define the model or part of the model.• Transfer Object Assembler constructs a immutablecomposite Transfer Object that represents data fromdifferent business components for the model• When a model is composed of a combination of manycomponents, the client must interact with numerous suchbusiness components to obtain all the data necessary torepresent the model.• Hence when model has multiple components, the clientsbecome tightly coupled to the model implementation andmake numerous remote method invocations to obtain data.
Transfer Object• Context: Application clients need to exchangedata with enterprise beans.• Problem: Some methods exposed by the businesscomponents return data to the client.• The client invokes a business objects getmethods multiple times until it obtains all theattribute values.• Every method call made to the business serviceobject is potentially remote.
Transfer Object: Problem• In EJB application such remote invocations usethe network layer regardless of the proximity ofthe client to the bean, creating a networkoverhead.• As the usage of the remote methods increases,application performance can significantlydegrade.• Therefore, using multiple calls to get methodsthat return single attribute values is inefficient forobtaining data values from an enterprise bean.
Transfer Object• Solution: Use a Transfer Object to encapsulatethe business data.• A single method call is used to send and retrievethe Transfer Object.• When the client requests the enterprise bean forthe business data, the enterprise bean canconstruct the Transfer Object, populate it with itsattribute values, and pass it by value to the client.• It reduces the number of remote calls and avoidsthe associated overhead.• Since the Transfer Object is passed by value tothe client, all calls to the Transfer Object instanceare local calls instead of remote methodinvocations.
Data Access Object• Context: Access to data varies depending on thesource of the data.• Access to persistent storage, such as database,varies depending on type of storage and thevendor implementation.• Problem: Persistent storage is implemented withdifferent mechanisms, with marked differences inthe APIs to access the different persistent storagemechanisms.• Access mechanisms, supported APIs, and featuresvary between different types of persistent stores.
Data Access Object: Problem• Applications that need to access data from a legacy ordisparate system are often required to use APIs thatmay be proprietary, creating a direct dependencybetween application code and data access code.• Including the connectivity and data access code withinthese components introduces a tight coupling betweenthe components and the data source implementationmaking it difficult and tedious to migrate theapplication from one type of data source to another.• When the data source changes, the components needto be changed to handle the new type of data source.
Data Access Object• Solution: Use a Data Access Object (DAO) toabstract and encapsulate all access to the datasource.• The DAO manages the connection with the datasource to obtain and store data.• The DAO completely hides the data sourceimplementation details from its clients.• The DAO adapts to different storage schemeswithout affecting its clients or businesscomponents
Decorator Pattern• The Decorator Pattern is used for addingadditional functionality to a particular object asopposed to a class of objects.• A Decorator, also known as a Wrapper, is an objectthat has an interface identical to an object that itcontains.• Any calls that the decorator gets, it relays to theobject that it contains, and adds its ownfunctionality along the way, either before or afterthe call.• This gives you a lot of flexibility, since you canchange what the decorator does at runtime, asopposed to having the change be static anddetermined at compile time by sub classing.
Decorator Pattern• A Decorator is a concrete instance of the abstractclass and is indistinguishable from the object thatit contains.• This can be used to great advantage, as you canrecursively nest decorators without any otherobjects being able to tell the difference, allowinga near infinite amount of customization.• Decorators add the ability to dynamically alterthe behavior of an object.• Good idea to use in a situation to change thebehavior of an object repeatedly during runtime.• It helps to add behavior or responsibilities to anobject.
Command pattern• A Command pattern is an object behavioralpattern used to achieve complete decouplingbetween the sender and the receiver.• A sender is an object that invokes an operation,and a receiver is an object that receives therequest to execute a certain operation.• With decoupling, the sender has no knowledge ofthe Receivers interface.• The term request here refers to the commandthat is to be executed.• The Command pattern allows to vary when andhow a request is fulfilled thus providing flexibilityas well as extensibility.
Command Pattern• Intent:• encapsulate a request in an object• allows the parameterization of clients with differentrequests• allows saving the requests in a queue• Implementation:• The Client asks for a command to be executed.• The Invoker takes the command, encapsulates it andplaces it in a queue, in case there is something else todo first, and the ConcreteCommand that is in charge ofthe requested command, sending its result to theReceiver.
Factory Pattern• Factory Method is a creational pattern which helps tomodel an interface for creating an object which at creationtime can let its subclasses decide which class to instantiate.• Factory Pattern is responsible for "Manufacturing" anObject.• It helps to instantiate the appropriate Subclass by creatingthe right Object from a group of related classes.• The Factory Pattern promotes loose coupling by eliminatingthe need to bind application-specific classes into the code.• The use of factories gives the programmer the opportunityto abstract the specific attributes of an Object into specificsubclasses which create them.• Define an interface for creating an object, but let thesubclasses decide which class to instantiate. The Factorymethod lets a class defer instantiation to subclasses.
Singleton Pattern• Singleton involves only one class which isresponsible to instantiate itself, to make sure itcreates not more than one instance; in the sametime it provides a global point of access to thatinstance.• The same instance can be used from everywhere,being impossible to invoke directly theconstructor each time.• Intent:• Ensure that only one instance of a class iscreated.• Provide a global point of access to the object.
Singleton Pattern• Implementation:• It involves a static member in the "Singleton"class, a private constructor and a static publicmethod that returns a reference to the staticmember.• The Singleton Pattern defines a getInstanceoperation which exposes the unique instancewhich is accessed by the clients.• Constructor is not accessible from outside of theclass.
Singleton: Specific Implementation issues• Thread-safe implementation: Singletons can be usedspecifically in multi-threaded application to make surethe reads/writes are synchronized.• Lazy instantiation: Synchronization can be veryexpensive considering the performance. When thesingleton object is already created it should bereturned without using any synchronized block.• Such optimization consist of checking in anunsynchronized block if the object is null and if not tocheck again and create it in an syncronized block. Thisis called double locking mechanism.
Singleton: Specific Implementation issues• Early instantiation using static field: The singleton object isinstantiated when the class is loaded and not when it is firstused, due to the fact that the instance member is declaredstatic.• Classes loaded by different classloaders: If a class(samename, same package) is loaded by 2 different classloadersthey represents 2 different clasess in memory.• Serialization: If Singleton class implementsjava.io.Serializable interface, when a singleton is serializedand then deserialized more than once, there will bemultiple instances of Singleton created. It can be avoidedby implementing the readResolve method.• Abstract Factory and Factory Methods implemented assingletons: Having 2 factories might have undesired effectswhen objects are created. Hence, to ensure that a factory isunique it should be implemented as a singleton, thusavoiding to instantiate the class before using it.