Dimit Chadha Java Technical Architect Javapathshala.com
What are DESIGN PATTERNS ?
Typically Pattern is:
Problem
A - SOLUTION To a - PROBMLEM In a - CONTEXT With - CONSEQUENCES
Forces
Solution Consequences
Benefits Related Patterns
Pattern is a best practice solution to a common recurring problem
Design Pattern
Typical solution to the problem Nearly a universal standard More of a template Mined from good designs Refactoring targets
Discovered, not created
Data structures that can be encoded in classes and reused Complex domain-specific designs for an entire application
Patterns Arose from Architecture and Anthropology - Christopher Alexander
Design Pattern Benefits Provides a well tested solution for a common problem Helps provide some design work Combinations of patterns tend to provide for reusable architecture
frameworks Develop better products. Allows learning from others experience. Don’t reinvent the wheel. Enable large-scale reuse of software architectures and also help document
systems Patterns explicitly capture expert knowledge and design tradeoffs and
make it more widely available Pattern names form a common vocabulary
Location of Design Patterns OO architecture
Global architecture Enterprise architecture
ORB
Subsystem
System architecture Application architecture
Frameworks
Macro-architecture
Design patterns Micro-architecture Objects
OO programming
Patterns Vs “Design” Patterns are designs. Patterns provide structure to “design” Patterns can capture OO design principles within a specific domain
Patterns Vs “Architecture” Design Patterns represent a lower level of system structure than “architecture” Patterns are applied to architecture Architecture is for the complete application
Key Elements of Patterns Item
Description
Name
All patterns have a unique name that identifies them
Intent
The purpose of the pattern
Problem
The problem that the pattern is trying to solve
Solution context
How the pattern provides a solution to the problem in the in which it shows up
Participants
The entities involved in the pattern
Consequences
Consequences of using the pattern. Investigates the forces at play in the pattern
Implementation
How the pattern can be implemented
Generic structure pattern
A standard diagram that shows a typical structure for the
structure of a class Structural
Creational
Constructing objects
Behavioral
object behavior
Design Patterns
Creational Design Patterns • Make the system independent of how objects are created, composed & represented • Abstract the instantiation process • Encapsulate the knowledge about concrete classes system uses • Hide how instances of these classes are created and assembled • Govern the what, when, who, and how of object creation
Factory Builder
Abstract Factory
Prototype
Creational Patterns
Singleton 9
Single Ton Pattern Intent: Ensure a class only has one instance, and provide a global point of access to it. Examples : System. in, System. out, AWT Thread Implementation public class Singleton Pattern { private static Singleton Pattern instance; public static Singleton Pattern getInstance(){ if (instance == null){ instance = new SingleTonPattern(); } return instance; }
}
public class SingleTonClient {
public static void main(String argv[]){ System.out.println("Creating One Instance"); SingleTonPattern stp1 = SingleTonPattern.getInstance(); System.out.println("Fisrt Instance Created::"+stp1); System.out.println("Creating Second Instance"); SingleTonPattern stp2=SingleTonPattern.getInstance(); System.out.println("Second Instance can't be Created"); System.out.println("Second Instance Not Created::"+stp2); } } UML Diagram
Factory Pattern Intent: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. Motivation: A database system needs to support multiple database drivers. The application can connect to different databases at runtime based on different driver and can anticipate which class will represent the connection. Eg JDBC DriverManager.getConnection Applicability: • Class can’t anticipate the class of the object it must create • A class wants it subclass to specify the object it creates • Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
Practical Example Suppose we have capture data from the database (which is nothing but the list of financial tx). Our object ive is to write this data into different finanacial tx formats like MT103,SAP,SIF etc depending upon on the user selection. The Simplest way (with out any desigjn pattern ) is to write some code like this : if (fileFormat.equalsIgnoreCase(“sap")) { parser = new xml(); } else if (fileFormat.equalsIgnoreCase("sif")) { parser = new Sif(); }else if (fileFormat.equalsIgnoreCase(“mt103")) { parser = new Mt103(); } else { throw new IllegalArgumentException("No parser for file format"); } But this looks like a very bad design as all is managed by the main class.
A wonderful way of doing this is to pass the processing the factory… public class ParserFactory { private ParserFactory() { } public static ParserFactory newInstance() { return new ParserFactory(); } public SuperParser newParser (String fileFormat) { SuperParser parser = null; if (fileFormat.equalsIgnoreCase(“sap")) { parser = new xml(); } else if (fileFormat.equalsIgnoreCase("sif")) { parser = new Sif(); }else if (fileFormat.equalsIgnoreCase(“mt103")) { parser = new Mt103(); } else { throw new IllegalArgumentException("No parser for file format"); } return parser; } }
public class FactoryPatternImpl { public static void main(String[] args) { ParserFactory factory = ParserFactory.newInstance(); SuperParser parser = factory.newParser("sif"); System.out.println(parser.getClass().toString()); parser.parse(); } } public class Sif extends SuperParser { public void parse(){ System.out.println("We have called the Sif"); } } public class xml extends SuperParser { public void parse(){ System.out.println("We have called the Sif"); } } public class SuperParser { public SuperParser(){ System.out.println("We are In Parser Super Class"); } public void parse(){ System.out.println("Super Parser parse()"); } }
UML Diagram
Builder Pattern Intent: Separate the construction of a complex object from its representation so that the same construction process can create different representations.
Motivation: The system needs to read and write data to an underlying operating system. The problem is that each operating system handles I/O differently. Need a solution that allows the “handler” to be changed Applicability: • The algorithm for creating a complex object should be independent of the parts that make up the object and how they’re assembled • The construction process must allow different representations for the object that’s constructed
The Builder pattern separates the construction of a complex object from its representation, so that the same construction process can create different representation. Practical Example This pattern is used by fast food restaurants to construct children's meals. Children's meals typically consist of a main item, a side item, a drink, and a toy (e.g., a hamburger, fries, coke, and toy car). Note that there can be variation in the contents of the children's meal, but the construction process is the same. Whether a customer orders a cheeseburger, or chicken, the process is the same. The employee at the counter directs the crew to assemble a main item, side item, and toy. These items are then placed in a bag. The drink is placed in a cup and remains outside of the bag. This same process is used at competing restaurants.
Also used to save the data captured from the web form & then use that data as per the requirement s. Here process of creating the builder is same but how we use the contents of the builder is as per requirement
Structural Patterns Help identify and describe relationships between entities Address how classes and objects are composed to form large structures • Class-oriented patterns use inheritance to compose interfaces or implementations • Object-oriented patterns describe ways to compose objects to realize new functionality, possibly by changing the composition at run-time Facade
Decorator
Bridge
Flyweight
Adapter
Proxy 19
AdapterPattern Intent: Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. Motivation: Two entities want to work together but there is an interface mismatch. Changing one interface to support the other would create a tight coupling. Need to wrap one interface so it supports the interactions. Applicability: • Want to use an existing class and its interface does not match • Want to create a reusable class that cooperates with unrelated classes The Adapter pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients. Practical Example: In the US, electrical outlets are three-pronged. When traveling to certain countries in Europe, electrical outlets require 2-prongs. To make US electronics work in Europe you can get a set of adapters to create compliance between the two interfaces.
public interface IRoundPeg { public void insertIntoHole(String msg); }
public interface ISqaurePeg { public void insertSquare(String msg);
}
public class RoundPeg implements IRoundPeg{ public void insertIntoHole(String msg) { System.out.println("RoundPeg insertIntoHole(): " + msg); } } public class SquarePeg implements ISqaurePeg { public void insertSquare(String str) { System.out.println("SquarePeg insert(): " + str); } } public class TestPegs { public static void main(String[] args) { SquarePeg squarePeg = new SquarePeg(); squarePeg.insertSquare("Inserting square peg..."); RoundPeg roundPeg = new RoundPeg(); roundPeg.insertIntoHole(“inserting hole peg”);
// WHAT TO DO TO INSERT A ROUND PED IN TO SQUARE PEG ? } }
/** * The PegAdapter class. This is the Adapter class. It adapts a RoundPeg to a SquarePeg. Its interface is that of a SquarePeg. */ public class PegAdapter implements ISqaurePeg { private RoundPeg roundPeg; public PegAdapter(RoundPeg roundPeg) { this.roundPeg = roundPeg; } public void insertSquare(String str) { roundPeg.insertIntoHole(str); } } public class TestPegs { public static void main(String[] args) { SquarePeg squarePeg = new SquarePeg(); squarePeg.insertSquare("Inserting square peg..."); RoundPeg roundPeg = new RoundPeg(); roundPeg.insertIntoHole(“inserting hole peg”);
} }
PegAdapter adapter = new PegAdapter(roundPeg); adapter.insertSquare("Inserting round peg...");
Output will be :
SquarePeg insert(): Inserting square peg... RoundPeg insertIntoHole(): Inserting round peg... RoundPeg insertIntoHole(): Inserting round peg...
This is by implementing the Adapter
UML Diagram
DecoratorPattern Intent: Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub classing for extending functionality, without breaking the interface.
Motivation: A system needs to provide consistent ability to read and write information across operating systems. It needs to support different approaches to write the data, the most primitive being binary. Applicability: • Add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects. • When extension by sub classing is impractical The Decorator attaches additional responsibilities to an object dynamically.
Although paintings can be hung on a wall with or without frames, frames are often added, and it is the frame which is actually hung on the wall. Prior to hanging, the paintings may be matted and framed, with the painting, matting, and frame forming a single visual component. Java’s IO capabilities
public interface IComponent { public void doStuff(); }
public class Component implements IComponent{ public void doStuff() { System.out.println("Do Suff"); } }
public interface Decorator extends IComponent { public void addedBehavior(); } public class ConcreteDecorator implements Decorator { IComponent component; public ConcreteDecorator(IComponent component) { super(); this.component = component; }
public void addedBehavior() { System.out.println("Decorator does some stuff too"); } public void doStuff() { component.doStuff(); addedBehavior(); } }
public class DecoratorClient { public static void main(String[] args) { IComponent comp = new Component(); Decorator decorator = new ConcreteDecorator(comp); decorator.doStuff(); } }
Result : Do Suff Decorator does some stuff too
Decorator addedBehavior()
Icomponent (doStuff)
FaçadePattern Intent: Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. Doesn't exposing details to the clients. The Facade defines a unified, higher level interface to a subsystem, that makes it easier to use. Motivation: Structuring a system into subsystems helps reduce complexity. A common design goal is to minimize the communication and dependencies between subsystems. A façade provides a single, simplified interface to the more general facilities of a subsystem.
Applicability: Want to provide a simple interface to a complex subsystem. Want to layer your subsystem Example: Consumers encounter a Facade when ordering from a catalog. The consumer calls one number and speaks with a customer service representative. The customer service representative acts as a Facade, providing an interface to the order fulfillment department, the billing department, and the shipping department.
public interface Store { public Goods getGoods(); }
public class FinishedGoodsStore implements Store { public Goods getGoods() { FinishedGoods finishedGoods = new FinishedGoods(); return finishedGoods; } } public class FinishedGoodsStore implements Store { public Goods getGoods() { FinishedGoods finishedGoods = new FinishedGoods(); return finishedGoods; } }
public class StoreKeeper { public Goods getGoods(String goodsType) { if (goodsType.equals("Packaging")) { PackingMaterialStore store = new PackingMaterialStore(); PackingMaterialGoods packingMaterialGoods = (PackingMaterialGoods)store.getGoods(); return packingMaterialGoods; }else if (goodsType.equals("Finished")) { FinishedGoodsStore store = new FinishedGoodsStore(); FinishedGoods finishedGoods = (FinishedGoods)store.getGoods(); return finishedGoods; }else { RawMaterialStore store = new RawMaterialStore(); RawMaterialGoods rawMaterialGoods = (RawMaterialGoods)store.getGoods(); return rawMaterialGoods; } }
The client will just access the StoreKeeper and ask for either finished goods, packaging material or raw material.
public class Client { public static void main(String[] args) { StoreKeeper keeper = new StoreKeeper(); RawMaterialGoods rawMaterialGoods = keeper.getGoods("RawMaterials"); } }
ProxyPatterns Intent: Provide a surrogate or placeholder for another object to control access to it. Motivation: A distributed programming systems wants to do remote garbage collection and needs to keep track of the number of remote references. To do this, the client must go through something that maintains that reference count behavior. Applicability: • Virtual Proxies: Delaying the creation and initialization of expensive objects until needed, • Remote Proxies: Providing a local representation for an object that is in a different address space. Eg Java RMI stub objects. The stub object acts as a proxy where invoking methods on the stub would cause the stub to communicate and invoke methods on a remote object • Protection Proxies: Proxy controls access to RealSubject methods, by giving access to some objects while denying access to others. • Smart References: Provides access to certain objects such as tracking the number of references to an object and denying access if a certain number is reached, as well as loading an object from database into memory on demand. Example : ATM or Cheque act as proxies to the Bank. Remote references in EJB Java’s RMI implementation
Consider an image viewer program that lists and displays high resolution photos. The program has to show a list of all photos however it does not need to display the actual photo until the user selects an image item from a list. public interface Image { public void showImage();
} RealSubject Implementation, which is the concrete and heavyweight implementation of the image interface. The High resolution image, loads a high resolution image from disk, and renders it to screen when showImage() is called. public class HighResolutionImage implements Image { public HighResolutionImage(String imageFilePath) { loadImage(imageFilePath); } private void loadImage(String imageFilePath) { // load Image from disk into memory, this is heavy and costly operation } public void showImage() { // Actual Image rendering logic } }
Proxy implementation, the image proxy is a virtual proxy that creates and loads the actual image object on demand, thus saving the cost of loading an image into memory until it needs to be rendered: public class ImageProxy implements Image { private String imageFilePath; //Private Proxy data private Image proxifiedImage; //Reference to RealSubject public ImageProxy(String imageFilePath) { this.imageFilePath= imageFilePath; } public void showImage() { // create the Image Object only when the image is required to be shown proxifiedImage = new HighResolutionImage(imageFilePath); // now call showImage on realSubject proxifiedImage.showImage(); }
CompositePattern Intent: Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly Motivation: User interfaces are made up of a composition of components. Each component may contain other components, which may contain other components. Applicability: • You want to represent part-whole hierarchies of objects • You want clients to be able to ignore the difference between compositions of objects & individual objects. Clients will treat all objects in the composite structure uniformly. Example: Arithmetic expressions are Composites. An arithmetic expression consists of an operand, an operator (+ - * /), and another operand. The operand can be a number, or another arithmetic expression. Thus, 2 + 3 and (2 + 3) + (4 * 6) are both valid expressions.
Bridge Pattern Intent: Decouple (separate) an object’s abstraction from its implementation so the two can vary independently Motivation: The typical way to deal with several possible implementations of an abstraction is through inheritance. However, this may bind an implementation to an abstraction, making it hard to extend, re-use, or modify. Applicability: • You want to avoid a permanent binding between an abstraction and its implementation • The abstractions and their implementations should be extensible by sub classing • Changes in the implementation of an abstraction should have no impact on clients; that is, their code should not have to be recompiled. A household switch controlling lights, ceiling fans, etc. is an example of the Bridge. The purpose of the switch is to turn a device on or off. The actual switch can be implemented as a pull chain, a simple two position switch, or a variety of dimmer switches. JDBC ODBC Driver
Behavioral Patterns The interactions between the objects should be such that they are talking to each other and still are loosely coupled. Describe algorithms, assignment of responsibility, and interactions between objects (behavioral relationships) Behavioral class patterns use inheritance to distribute behavior Behavioral object patterns use composition Deal with dynamic interactions among societies of classes and objects
35
Chain of Responsibility Visitor
Command
Template Method
Interpreter
Behavioral Patterns
Strategy
State
Iterator
Mediator
Observer
Memento
CommandPattern Intent: Encapsulate a request as an object, letting you parameterize clients with different requests Motivation: You need to be able to change the implementation of an operation dynamically, at run-time by specifying an operation as an object Applicability: Decouple implementation of operation Creation consistent action structure The Command pattern allows requests to be encapsulated as objects, thereby allowing clients to be parameterized with different requests. Data-driven pattern. The client invokes a particular module using a command Struts Action commands
A classic example of this is a restaurant. A customer goes to restaurant and orders the food according to his/her choice. The waiter/ waitress takes the order (command, in this case) and hands it to the cook in the kitchen. The cook can make several types of food and so, he/she prepares the ordered item and hands it over to the waiter/waitress who in turn serves to the customer. First thing is the Order. The order is made of command which the customer gives the waiter. The other thing is the waiter who takes the order and forwards it to the cook. Now, here, the waiter takes command and wraps it in an order, the order is associated to a particular customer. For, the cook, the order is associated to a cook and also Food is associated to the Order. The order is an object which depends on the command. The food item will change as soon as the command changes. This is loose-coupling between the client and the implementation.
ObserverPattern Intent: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically Motivation: An object-relational-mapping framework needs to keep track of changes made in a database and map them to an object and vice versa Applicability: When a change to one object requires changing others, and you don't know how many objects need to be changed. When an object should be able to notify other objects without making assumptions about who these objects are " Some auctions demonstrate this pattern. Each bidder possesses a numbered paddle that is used to indicate a bid. The auctioneer starts the bidding, and "observes“ when a paddle is raised to accept the bid. The acceptance of the bid changes the bid price, which is broadcast to all of the bidders in the form of a new bid.
StrategyPattern Intent: Define a family of algorithms, encapsulate each one, and make them interchangeable. A Strategy defines a set of algorithms that can be used interchangeably.
Motivation: A system needs to change how it connects to the web depending on the underlying security within an organization. It may be able to connect directly, use a proxy, or require security. Applicability: You need different variants of an algorithm. Modes of transportation to an airport is an example of a Strategy. Several options exist, such as driving one's own car, taking a taxi, an airport shuttle, a city bus Any of these modes of transportation will get a traveler to the airport, and they can be used interchangeably. The traveler must chose the Strategy based on tradeoffs between cost, convenience, and time. Comparator / Comparable interfaces in Java collections
WebTierPatterns Application construction ! " Applications built by many groups of developers ! " Groups have different skills ! " Groups have different objectives ! " Groups have different timelines ! " This translates into various pieces of the application being developed independently ! " Application use ! " Applications often also need to support multiple clients ! " Different clients can interact with application in different ways ! " Share business data in different ways ! " Interactions follow different flows ! " This increases the complexity and risk of an application
Model View Controller Front Controller View Helper Composite View
Business Delegate Dispatcher View Service To Worker
FrontController The “front door” to your application Generally a pre-processor, but can be used for post processing too ! " Often used to enforce ! " Validation rules ! " Authentication constraints ! " Dispatching of requests ! " Session management Front Controller Servlet Strategy ! " This is the most common approach ! " All requests route through the servlet ! " Front Controller processing is more logically separated from the view Front Controller JSP Strategy ! " Generally, this is undesirable due to the mismatch of lowlevel processing and view processing ! " Tends to lead to complicated JSP code
Front Controller
Advantages
Promotes reuse of common code that is needed for all requests . Promotes flexibility Easier to maintain
Avoid fat controllers .
Do not restrict site to one controller. Different subsystems could have their own controllers.
Business Delegate Plain Java classes that hide EJB API complexity by encapsulating code required to discover, delegate to and recover from invocations on the session and message façade EJB layers. Use on large projects where the web team is separate from the EJB team . Business Delegate ! " Used to provide a façade over a complex business tier ! " Normally, presentation components interact with business services directly, which may cause problems ! " If the business tier API changes, it affects the presentation tier ! " Heavy interaction with the business tier may result in too many network calls ! " A Business Delegate can perform caching and throttling
Business Delegate as a Proxy ! " The Business Delegate exposes the same interface as the business tier ! " Calls to the Business Delegate can be forwarded to the business tier ! " Data can also be cached and calls short-circuited ! " This can reduce network calls and increase performance
Business Delegate as an Adapter ! " Excellent for communication with disparate business components ! " For example, communication with a web service component could be accomplished ! " The delegate would parse the XML request ! " The data in the request could be sent to an existing, non-XML aware, business tier ! " A response could work the same way
Dispatcher View Dispatcher is responsible for view management and navigation . Can be encapsulated within a controller, a view or as a separate
component. Dispatcher view suggests deferring content retrieval to the time of
view processing. Dispatcher sequence Combines Front Controller and View Helper ! " May also involve Composite View
Model VIEW CONTROLLER
The browser makes a request to web server by request URL. The web server (Apache, WEBrick, etc.) receives the request. It uses routes to find out which controller to use: the default route pattern is “/controller/action/id” as defined in configuration file. The web server then uses the dispatcher to create a new controller, call the action and pass the parameters.
Controllers do the work of parsing user requests, data submissions, cookies, sessions and the “browser stuff”. Models are PHP classes. They talk to the database, store and validate data, perform the business logic and otherwise do the heavy lifting. Views are what the user sees: HTML, CSS, XML, JavaScript, JSON. They’re the sales rep putting up flyers and collecting surveys, at the manager’s direction. Views are merely puppets reading what the controller gives them. They don’t know what happens in the back room. The controller returns the response body (HTML, XML, etc.) & metadata (caching headers, redirects) to the server. The server combines the raw data into a proper HTTP response and sends it to the user.
Model VIEW CONTROLLER
The pattern isolates "domain logic" (the application logic for the user) from input and presentation (UI), permitting independent development, testing and maintenance of each.
The model is used to manage information and notify observers when that information changes. The model is the domain-specific representation of the data upon which the application operates. Domain logic adds meaning to raw data (for example, calculating whether today is the user's birthday, or the totals, taxes, and shipping charges for shopping cart items). When a model changes its state, it notifies its associated views so they can be refreshed. Many applications use a persistent storage mechanism such as a database to store data. MVC does not specifically mention the data access layer because it is understood to be underneath or encapsulated by the model. Models are not data access objects; however, in very simple apps that have little domain logic there is no real distinction to be made. Active Record is an accepted design pattern which merges domain logic and data access code - a model which knows how to persist itself. The view renders the model into a form suitable for interaction, typically a user interface element. Multiple views can exist for a single model for different purposes. A viewport typically has a one to one correspondence with a display surface and knows how to render to it. The controller receives input and initiates a response by making calls on model objects. A controller accepts input from the user and instructs the model and viewport to perform actions based on that input. An MVC application may be a collection of model/view/controller triplets, each responsible for a different UI element. MVC is often seen in web applications where the view is the HTML or XHTML generated by the app. The controller receives GET or POST input and decides what to do with it, handing over to domain objects (i.e. the model) that contain the business rules and know how to carry out specific tasks such as processing a new subscription.
MVC web application frameworks: Aranea Cocoon Induction JSF Makumba Web development framework in the form of JSP Tag Library and Java API that is based on MVC, but willingly breaks it Oracle Application Framework Play Framework PureMVC, a framework for Java Sling, used to create content based applications on top of JCR. Supported scripting languages are JSP, server-side JavaScript, Ruby, Velocity Spring MVC Framework Struts Struts2 Stripes Tapestry Wavemaker, a WYSIWYG development platform for Ajax web applications.[7] WebObjects WebWork Wicket Web Dynpro Java
Service Locator Pattern 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.