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.


4 comments:

  1. Very nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
    Web Development Company in India

    ReplyDelete
  2. 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