1 / 29

Java Design Pattern

Java Design Pattern. By Shishir Kumar Contact: Shishirroy2000@gmail.com. Agenda. Decorator Adaptor Bridge Template Strategy . Adapter Pattern.

aldan
Download Presentation

Java Design Pattern

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Design Pattern By Shishir Kumar Contact: Shishirroy2000@gmail.com

  2. Agenda • Decorator • Adaptor • Bridge • Template • Strategy

  3. Adapter Pattern • Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

  4. Adapter Cont. • AC Power Adapters • Electronic products made for the USA cannot be used directly with electrical outlets found in most other parts of the world • US 3-prong (grounded) plugs are not compatible with European wall outlets • To use, you need either • An AC power adapter, if the US product has a “universal” power supply, or • An AC power convertor/adapter, if it doesn’t

  5. Type Of Adapter • Object Adapters Object Adapters use a compositional technique to adapt one interface to another. The adapter inherits the target interface that the client expects to see, while it holds an instance of adaptee. Object adapters enable the client and the adaptee to be completely decoupled from each other. Only the adapter knows about both of them. • Class Adapters Class adapters use multiple inheritance to achieve their goals. As in the object adapter, the class adapter inherits the interface of the client's target. However, it also inherits the interface of the adaptee as well. Since Java does not support true multiple inheritance, this means that one of the interfaces must be inherited from a Java Interface type. Note that either or both of the target or adaptee interfaces could be an Java Interfaces. The request to the target is simply rerouted to the specific request that was inherited fro the adaptee interface.

  6. Object Vs. Class Adapters • Difference between Object Adapters and Class Adapters • As Object Adapter uses composition it can not only adapt an adaptee class, but any of its subclasses. It is flexible. • Class Adapter is committed to only one adaptee. But again it has an advantage as no need to implement the entire adaptee. It can just override the behaviour of adaptee and also can override the behavior as it is sub classing. • Note that class adapters have a problem with name conflicts if methods of the same signature exist on both the target and the adaptee. Note that just because two objects have methods that have the same signature (syntax), it does not guarantee that the two methods have the same meaning or behavior (sematics). That is, the two methods do not necessarily map directly to each other. Object adapters do not have this problem. • Class adapters are simpler than object adapters in that they involve fewer classes and are useful if total decoupling of the client and adaptee is not needed.

  7. Adaptor - Case Study • Client only understands the SquarePeg interface for inserting pegs using the insert() method. At back end application should reuse insert logic within round pegs? • One Way Adaptor (Object Adaptor) • Two Way Adaptor (Class Adaptor) Case Study II: Build web application where user input data from UI. Data can be saved within application database and/or routed to mainframe. Mainframe is proprietary system and we do not have control over same.

  8. Adaptor - Class Diagram • The client makes a request on the adapter by invoking a method from the target interface on it • The adapter translates that request into one or more calls on the adaptee using the adaptee interface • The client receives the results of the call and never knows there is an adapter doing the translation

  9. Reference Class Diagram

  10. Adaptor - Where To Use • We can not change the library interface, since we may not have its source code. Even if we did have the source code, we probably should not change the library for each domain-specific application • Sometimes a toolkit or class library can not be used because its interface is incompatible with the interface required by an application • You want to create a reusable class that cooperates with unrelated classes with incompatible interfaces • Implementation Issues How much adapting should be done? Simple interface conversion that just changes operation names and order of arguments Totally different set of operations

  11. Adaptor - Real World Example • Before Java’s new collection classes, iteration over a collection occurred via java.util.Enumeration hasMoreElements() : boolean nextElement() : Object • With the collection classes, iteration was moved to a new interface: java.util.Iterator hasNext(): boolean next(): Object remove(): void • There’s a lot of code out there that makes use of the Enumeration interface hence Iterator use Adaptor pattern

  12. Bridge Pattern • Decouple an abstraction or interface from its implementation so that the two can vary independently

  13. Bridge - Case Study • Simulate Persistence API From application layer developer want to fetch information from persistence system. Persistence system can be RDBMS Database (can be any data base E.g. Oracle, Sybase or File System). In this scenario there are two interface a) Application layer – End client interactb) Persistence layer – Interface define persist/fetch

  14. Bridge - Class Diagram

  15. Reference Class Diagram

  16. Bridge - Where To Use • Want to separate abstraction and implementation permanently • Hide implementation details from clients • Want to improve extensibility Real World Example: • DAO , Persistence Layer • Image (jpeg/png) display on different Operation System The image structure is the same across all operating systems, but the how it's viewed (the implementation) is different on each OS.

  17. Template Pattern • The Template Method defines the steps of an algorithm and allows sub class to provide the implementation for one or more steps. • Template Method let subclass redefine certain steps of an algorithm without changing the algorithm’s structure. • Hook –behavior that can be overridden within subclass to control algorithm behavior.

  18. Template - Case Study • Application for processing flat file for a) Stock and b) Derivatives. Requirement • Stock support CSV format where as Derivative support txt • Stock data is separated by delimiter “,” where as Derivative data within Flat file separated by “|”. Data is persisted within database. • System can configure logging into system optionally for data under process.

  19. Template Class Diagram

  20. Reference Class Diagram

  21. Template - Where To Use • Want to have control over algorithm to avoid duplicate code • Use Template if you are aware of requirement complexity/algorithm. This is for code reuse and allow subclass to specify behavior. Real World Example: • Servlet (explained next slide) • Java – Arrays sort, mergeSort (Refer Head First Book) • JFrame – update() (Refer Head First Book) • HibernateCallback used in HibernateTemplate's execute(..) methods (Refer Spring Blogs) • Struts - RequestProcessor

  22. Template - Real World Example • Servlet Life Cycle • init() • service() • destroy() • Service method is an abstract method in GenericServlet Class. • HttpServlet extends GenericServlet and implement service method. • Based on HTTP request type, HTTPServlet invokes • - doGet, doPost, doHead, doPut, doDelete, doTrace, doOptions • Developers extend HttpServlet and write meaningful method - doGet, doPost • Template - HttpServlet service method define template for handling HTTP requests. • Hollywood Principle - "Don't call me, I will call you“ • Template method enforces "Open Closed principle". A class should be open for extension, but closed for modification.

  23. Strategy Pattern • Strategy pattern defines a family of algorithms, encapsulates each one and makes them interchangeable. • Strategy lets the algorithm vary independently from clients that use it. • Subclasses decide how to implement steps in an algorithm.

  24. Strategy - Case Study • Application for processing flat file for a) Stock and b) Derivatives. Requirement • Validate File format/type against system configuration • Stock/Derivative data can be stored in database or content repository (as XML) • File can be routed to third party system Bloomberg (via SOAP) or other customer (JMS). • Investment Bank can do below action • Indus Bank: validate, store data (database) and route to Bloomberg • USB Bank: validate, store (Repo) and route to Bloomberg • ABC Bank: validate, store (DB) and route to other customer

  25. Make it simple • Operation: • Validate - common method to validate File format/type (independent of investment type – Stock/Derivative) • Parse and Store- parse data based on investment type (Stock/Derivative) and store within database or content repository system in XML format • Route – file to third party system (via SOAP) or Content repository system

  26. Strategy - Class Diagram

  27. Reference Class Diagram

  28. Strategy - Where to use • Many related classes differ only in their behavior • You need different variants of an algorithm • An algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures. • A class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class • Real World Example: • Swing GUI Text components • Java AWT

  29. Benefits and Liabilities • Benefits • Provides an alternative to subclassing the Context class to get a variety of algorithms or behaviors • Eliminates large conditional statements • Provides a choice of implementations for the same behavior • Liabilities • Increases the number of objects • All algorithms must use the same Strategy interface

More Related