Sunday 30 October 2011

Design Patterns - Intention, Motivation and Examples


Design patterns provide a fundamental foundation to building maintainable and scalable software. Understanding how the patterns work, why they provide a benefit, and when to use them helps to ensure that software is built from reusable object oriented components. In the text below, the patterns are grouped as per software architecture tradition into three categories - structural patterns, behavioral patterns and creational patterns.

The first set of patterns described in the table below is what is coined as Structural patterns. These patterns describe how objects and classes can be combined to form larger structures.

Structural
Pattern
Info
Adapter (Wrapper)
Intent: Converts the interface of a class into another interface clients expect. This lets classes work together that couldn't otherwise because of incompatible interfaces.

Example 1: 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.

Example 2: Commonly used to make independently developed class libraries work together.
Bridge (Handle/Body)
Intent: Decouple (separate) an abstraction from its implementation so that the two can vary independently.

Example 1: 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.

Example 2: JDBC ODBC Bridge, where both JDBC and ODBC can change and there are no implications if one changes.
Composite (Handle/Body)
Intent: Compose objects into tree structures to represent part-whole hierarchies. Lets clients treat individual objects and compositions of objects uniformly.

Example 1: Although the example is abstract, 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.

Example 2: Swing where all components are containers, allowing components to be held within components.
Decorator (Wrapper)
Intent: Attach additional responsibilities to an object dynamically. Provide a flexible alternative to sub-classing for extending functionality.

Example 1: 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.

Example 2: Java I/O where InputStream and OutputStream are standard interfaces where their capabilities can be extended by being decorated with other compatible streams.
Façade
Intent: Provide a unified interface to a set of interfaces in a subsystem. Defines a high -level interface that makes the subsystem easier to use.

Example 1: 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.

Example 2: Web Service
Flyweight
Intent: Use sharing to support large numbers of fine grained objects efficiently.

Example 1: The public switched telephone network is an example of a Flyweight. There are several resources such as dial tone generators, ringing generators, and digit receivers that must be shared between all subscribers. A subscriber is unaware of how many resources are in the pool when he or she lifts the hand set to make a call. All that matters to subscribers is that dial tone is provided, digits are received, and the call is completed.

Example 2: Connection pools and loggers (java.util.logging)
Proxy (Surrogate)
Intent: Provide a surrogate or placeholder for another object to control access to it.

Example 1: As shareholders in a company, you can either go to a meeting and vote, or you can place a proxy vote. The proxy vote is handled by an intermediary, but represents the actual vote.

Example 2: Remote interfaces in EJB and Java’s RMI implementation.

The next pattern set is referred to as Behavioral patterns. These prescribe the way objects interact with each other. They help make complex behavior manageable by specifying the responsibilities of objects and the ways they communicate with each other. 

Behavioral
Pattern
Info
Chain of Responsibility (Handle/Body)
Intent: Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

Example 1: Mechanical coin sorting banks use the Chain of Responsibility. Rather than having a separate slot for each coin denomination coupled with receptacle for the denomination, a single slot is used. When the coin is dropped, the coin is routed to the appropriate receptacle by the mechanical mechanisms within the bank.

Example 2: Event handling mechanism pre Java 1.1
Command (Action / Transaction)
Intent: Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

Example 1: The "check" at a diner is an example of a Command pattern. The waiter or waitress takes an order, or command from a customer, and encapsulates that order by writing it on the check. The order is then queued for a short order cook. Note that the pad of "checks" used by different diners is not dependent on the menu, and therefore they can support commands to cook many different items.

Example 2: Java’s Threading system
                     Java’s Swing action commands
                     Struts Action commands.
Interpreter
Intent: Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

Example 1: Musicians are examples of Interpreters. The pitch of a sound and its duration can be represented in musical notation on a staff. This notation provides the language of music. Musicians playing the music from the score are able to reproduce the original pitch and duration of each sound represented.

Example 2: HTML and XML Parsers
Iterator (Cursor)
Intent: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Example 1: On early television sets, a dial was used to change channels. When channel surfing, the viewer was required to move the dial through each channel position, regardless of whether or not that channel had reception. On modern television sets, a next and previous button are used. When the viewer selects the "next" button, the next tuned channel will be displayed. Consider watching television in a hotel room in a strange city. When surfing through channels, the channel number is not important, but the programming is. If the programming on one channel is not of interest, the viewer can request the next channel, without knowing its number.

Example 2: Java Collections API
Mediator
Intent: Define an object that encapsulates how a set of objects interact. Promotes loose coupling by keeping objects from referring to each other explicitly and it lets you vary their interactions independently.

Example 1: The control tower at a controlled airport demonstrates this pattern very well. The pilots of the planes approaching or departing the terminal area communicate with the tower, rather than explicitly communicating with one another.
The constraints on who can take off or land are enforced by the tower. It is important to note that the tower does not control the whole flight. It exists only to enforce constraints in the terminal area.

Example 2: A Software Bus
Memento (Token)
Intent: Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.

Example 1: This pattern is common among do-it-yourself mechanics repairing drum brakes on their cars. The drums are removed from both sides, exposing both the right and left brakes. Only one side is disassembled, and the other side serves as a Memento of how the brake parts fit together. Only after the job has been completed on one side is the other side disassembled. When the second side is disassembled, the first side acts as the Memento.

Example 2: HTTP Sessions
                      Cookies
                      Serialized Objects 
Observer (Dependents, Publish-Subscribe)
Intent: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Example 1: 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.

Example 2: Most UI toolkits
                ORM Frameworks
State
Intent: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

Example 1: This pattern can be observed in a vending machine. Vending machines have states based on the inventory, amount of currency deposited, the ability to make change, the item selected, etc. When currency is deposited and a
selection is made, a vending machine will either deliver a product and no change, deliver a product and change, deliver no product due to insufficient currency on deposit, or deliver no product due to inventory depletion.

Example 2: Web Servers
                      Real-time software
Strategy (Policy)
Intent: Define a family of algorithms, encapsulate each one, and make them interchangeable. Lets the algorithm vary independently from clients that use it.

Example 1: 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, or a limousine service. For some airports, subways and helicopters are also available as a mode of transportation to the airport. 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.

Example 2: Comparator / Comparable interfaces in Java Collections.
Template Method
Intent: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

Example 1: Home builders use the Template Method when developing a new subdivision. A typical subdivision consists of a limited number of floor plans, with different variations available for each floor plan. Within a floor plan, the foundation, framing, plumbing, and wiring will be identical for each house. Variation is introduced in the latter stages of construction to produce a wider variety of models.

Example 2: Template-oriented websites
                     CMS
Visitor (Agent)
Intent: Represent an operation to be performed on the elements of an object structure. Lets you define a new operation without changing the classes of the elements on which it operates.

Example: This pattern can be observed in the operation of a taxi company. When a person calls a taxi company he or she becomes part of the company's list of customers. The company then dispatches a cab to the customer (accepting a visitor). Upon entering the taxi, or Visitor, the customer is no longer in control of his or her own transportation, the taxi (driver) is.

Finally, the last of set of patterns we will summarize are the Creational patterns. These patterns are used when a decision must be made at the time a class is instantiated.

Creational
Pattern
Info
Abstract Factory
(Kit)
Intent: Provides an interface for creating families of related or dependent objects without specifying their concrete class.

Example 1: The pattern is found in the sheet metal stamping equipment used in the manufacture of Japanese automobiles. The stamping equipment is an Abstract Factory which creates auto body parts. The same machinery is used to stamp right hand doors, left hand doors, right front fenders, left front fenders, hoods, etc. for different models of cars. Through the use of rollers to change the stamping dies, the concrete classes produced by the machinery can be changed within three minutes.

Example 2: 
java.sql.Connection allows the creation of Statements, PreparedStatements, CallableStatements for each database flavor.

javax.swing.LookAndFeel allows switching between several L&F for the components displayed.
Builder
Intent: Separate the construction of a complex object from its representing so that the same construction process can create different representations.
                                                                                        
Example 1: The 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, fires, 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 hamburger, cheeseburger, or chicken the process is the same. The employee at the counter directs the crew to assemble a main item, side item, a 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.

Example 2: Creating an Input Stream in Java delegates the creation of an underlying OS Specific input stream to a native library. This construction process is exactly the same from client perspective but how the object is created may differ.
Factory Method
(Virtual Constructor)
Intent: Define an interface for creating an object, but let subclasses decide which class to instantiate. Lets a class defer instantiation to subclasses.

Example 1: Injection molding presses demonstrate this pattern. Manufacturers of plastic toys process plastic molding powder, and inject the plastic into molds of the desired shapes. The class of toy (car, action figure, etc.) is determined by the mold.

Example 2:
        java.net.URLConnection – allows users to decide which protocol to use.
         JDBC DriverManager.getConnection
Singleton
Intent: Ensure a class only has one instance and provide a global point of access to it.

Example 1: The Singleton pattern in named after the singleton set, which is defined to be a set containing one element. The office of the President of the United States is a Singleton. The United States Constitution specifies the means by which a president is elected, limits the term of office, and defines the order of succession. As a result, there can be at most one active president at any given time. Regardless of the personal identity of the active president, the title, “The President of the United States” is a global point of access that identifies the person in the office.

Example 2:  Logger
                      Configuration
                      Accessing resources in shared mode
                      System.in, System.out, System.err
  AWT Thread
Prototype
Intent: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

Example 1: Prototypes of new products are built prior to full production, but in this example, the prototype is passive, and does not participate in copying itself. The mitotic division of a cell, resulting in two identical cells, is an example of a prototype that plays an active role in copying itself and thus, demonstrates the Prototype pattern. When a cell splits, two cells of identical genotype result. In other words, the cell clones itself.

Example 2:  The clone method in Java.


27 comments:

  1. Even the Essay Writers know that a well-designed website will draw more clients into reading the site’s content. It is therefore good for the web developers and programmers to be well used to these design patterns. One of the benefits of reading such tutorials is that the authors always ensure that the content is simplified.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Your new valuable key points imply much a person like me and extremely more to my office workers. With thanks from every one of us.

    Best AWS Training in Chennai | Amazon Web Services Training in Chennai

    AWS Training in Bangalore | Amazon Web Services Training in Bangalore

    ReplyDelete
  4. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

    angularjs Training in chennai
    angularjs Training in chennai

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    angularjs-Training in velachery

    ReplyDelete
  5. Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.
    python interview questions and answers | python tutorials

    ReplyDelete
  6. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

    ReplyDelete
  7. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging.
    Data Science course in rajaji nagar
    Data Science with Python course in chenni
    Data Science course in electronic city
    Data Science course in USA
    Data science course in pune | Data Science Training institute in Pune
    Data science course in bangalore

    ReplyDelete
  8. Thanks for this article.You can visit my website:3d background parallax

    ReplyDelete
  9. There are numerous parts of this article on which I agree with you. You have created neural connections in my mind not utilized frequently. Much thanks to you for getting my neurons bouncing.


    SEO services in kolkata
    Best SEO services in kolkata
    SEO company in kolkata
    Best SEO company in kolkata
    Top SEO company in kolkata
    Top SEO services in kolkata
    SEO services in India
    SEO copmany in India

    ReplyDelete
  10. Thank you for taking the time to provide us with your valuable information.
    Visit Data Science Online Training Hyderabad!

    ReplyDelete
  11. Hi This is SRK i'm suggesting you this is app Busuu Apk

    ReplyDelete
  12. Truly quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue to post. Much obliged for sharing.data science training in delhi

    ReplyDelete
  13. Hello your post is very helpful, thanks for wonderful information sharing. When you go about Find information and tips on Coffee Culture Around the World.
    Hello your post is very helpful, thanks for wonderful information sharing. When you go about Find information and tips on left breast
    Hello your post is very helpful, thanks for wonderful information sharing. When you go about Find information and tips on tongue scraper
    Hello your post is very helpful, thanks for wonderful information sharing. When you go about Find information and tips on blogger outreach
    Hello your post is very helpful, thanks for wonderful information sharing. When you go about Find information and tips on thick toenail
    Hello your post is very helpful, thanks for wonderful information sharing. When you go about Find information and tips on High da guest post
    Hello your post is very helpful, thanks for wonderful information sharing. When you go about Find information and tips on Women's Unstitched Summer Lawn Collection
    Hello your post is very helpful, thanks for wonderful information sharing. When you go about Find information and tips on Kamar Dard Ka ilaj

    ReplyDelete
  14. 6times ad asd fsdf sjfkg ajkfhud fhdsjkfh sdhflkshfl ks

    ReplyDelete
  15. You have done a great job. I will definitely dig it and personally recommend to my friends. I am confident they will be benefited from this site. data scientist course in kanpur

    ReplyDelete
  16. The fashion of blouse back neck designs catalogs changes every year. Let's take a look at some of the most beautiful saree blouse neck designs

    ReplyDelete
  17. I am a new user of this site so here i saw multiple articles and posts posted by this site,I curious more interest in some of them hope you will give more information on this topics in your next articles.data science certification course in chennai

    ReplyDelete
  18. Dear friend, This is the post I was looking for High DA guest post. I am very happy to finally read about the Thank you very much. Your post was of great help to me.

    ReplyDelete
  19. Broken Planet Sweatpants offers a variety of casual trousers such as track pants or jogging pants & sweatpants to style up with either a t-shirt or hoodie for an extremely classy look. These are loose-fit pants made of breathable, soft & comfortable material.
    https://brokenplanetmarkets.net/

    ReplyDelete