Thursday, April 14, 2011

Design Pattern:Decorator

The Decorator attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.Also called as Wrapper.

Problem

Sometimes we want to add responsibilities to individual objects (aTextView ) not to an entire class. ( i.e. how to give control to client to decorate the component with a border / a scroll bar )

Illustration:

image

image

Solution

  • One way to add responsibilities is with inheritance.Inheriting a border with another class puts a border along very subclass instance ( inflexible solution ).
  • A more flexible approach is to enclose the component in another objects that adds the border. The enclosing object is called Decorator.
  • The Decorator confirm to interface of the component it decorate so that its presence is transparent to its components clients.

Applicability

Use Decorator

  • To add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.
  • For responsibilities that can be withdrawn.
  • When extension by subclassing in impractical. Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination. Or a class definition may be hidden or otherwise unavailable for subclassing.

Structure

image

Collaborations

Decorator forwards requests to its Component object. It may optionally perform additional operations before and after forwarding the request.

Consequences

  • More flexibility than static inheritance:
    1. to add or delete responsibilities to objects at runtime simply by attaching and detaching them.
    2. Providing different decorator classes for a specific component class lets you mix and match responsibilities.
  • Avoids feature-laden classes high up in the hierarchy:
    1. Decorator offers a pay-as-you-go approach to adding responsibilities.Instead of trying to support all features in a complex, customizable class, you can define simple class and add functionality incrementally with Decorator objects.
  • A decorator and its component aren’t identical:
    1. A decorator acts as a transparent enclosure.
  • Lots of little objects :
    1. Decorator often results in system composed of lots of little objects that all look like, this may leed to maintenance nightmare and hard to learn.

Model

image

Related Patterns

Adapter: Adapter changes an object's interface, Decorator enhances an object's responsibilities. Decorator is thus more transparent to the client. As a consequence, Decorator supports recursive composition, which isn't possible with pure Adapters

Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface

Composite: A decorator can be viewed as a degenerate composite with only one component. However, a decorator adds additional responsibilities—it isn’t intended for object aggregation.

Design Pattern: Abstract Factory

The purpose of the Abstract Factory is to provide an interface for creating families of related objects, without specifying concrete classes.

Problem:

• How should one go about designing applications which have to be adopted to different Look and feel standards?

Solution:

•One could solve this problem by defining abstract widgets factory class that declares an interface for creating each basic kind of widgets ( control ) .

•There is also an abstract class for each kind of widget, and concrete sub classes implement widgets for specific look and standards.

Illustration:

image

Applicability:

Use the Abstract Factory pattern when

  • A system should be independent of how its products are created, composed, and represented.
  • A system should be configured with one of multiple families of products.
  • A family of related product objects is designed to be used together, and you need to enforce this constraint.
  • You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

Structure:

image

Collaborations

Normally a single instance of a ConcreteFactory class is created at run-time. This concrete factory creates product objects having a particular implementation. To create different product objects, clients should use a different concrete factory.

AbstractFactory defers creation of product objects to its ConcreteFactory subclass.

Consequences

  • It isolates concrete classes.
  • It makes exchanging product families easy.
  • It promotes consistency among products.
  • Supporting new kinds of products is difficult.

Model:

image

AbstractFactory classes are often implemented with factory methods, but they can also be implemented using Prototype.

Thursday, April 7, 2011

Design Pattern: Observer

The Observer defines a one to many relationship, so that when one object changes state, the others are notified and updated automatically.

The Observer design pattern is about passing notifications around to update a set of objects when some important event has occurred. You can add new observer objects at runtime and remove them as needed. When an event occurs, all registered observers are notified. Below Figure shows how it works; an observer can register itself with the subject.

image
And another observer, Observer 2, can register itself as well, as shown in below figure

image

Now the subject is keeping track of two observers. When an event occurs, the subject notifies both observers.

image

Illustration:

Picture1

Solution:

The observer pattern describes how to establish these relationships. The key objects in this pattern are subject and observer.

  • A subject may have any number of dependent observer.
  • All observers are notified whenever the subject undergoes a change in state.
  • In response, each observer will query the subject to synchronize its state with the subject’s state.

Applicability:

Use the Observer pattern in any of the following situations:

  • When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.
  • 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. In other words, you don’t want these objects tightly coupled.

Structure

image

Collaborations

  • ConcreteSubject notifies its observers whenever a change occurs that could make its observers’ state inconsistent with its own.
  • After being informed of a change in the concrete subject, a ConcreteObserver object may query the subject for information. ConcreteObserver uses this information to reconcile its state with that of the subject.

Consequences

  • Abstract coupling between Subject and Observer
  • Support for broadcast communication.
  • Unexpected updates

Model

image

Design Pattern: Proxy

The Proxy provides a surrogate or place holder to provide access to an object. You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are actually requested by the client.

Say that you’ve got some local code that’s used to dealing with a local object as shown in the figure below

image

 

 

 

 

 

But now say that you want to deal with some remote object, somewhere else in the world. How can you make the local code think it’s dealing with a local object still when in fact it’s working with that remote object?

With a proxy. A proxy is a stand-in for another object that makes the local code think it’s dealing with a local object. Behind the scenes, the proxy connects to the remote object, all the while making the local code believe it’s working with a local object, as you can see in figure below

image

Illustration :problem

Consider a document editor ( Html creator ) that can embed graphical objects in a document. Some graphical objects, like large raster images, can be expensive to create. But opening a document should be fast, so we should avoid creating all the expensive objects at once when the document is opened. This isn’t necessary anyway, because not all of these objects will be visible in the document at the same time.

These constraints would suggest creating each expensive object on demand, which in this case occurs when an image becomes visible.

But what do we put in the document in place of the image? And how can we hide the fact that the image is created on demand so that we don’t complicate the editor’s implementation?

Illustration: solution

  • The solution is to use another object, an image proxy, that acts as a stand-in for the real image.
  • The proxy acts just like the image and takes care of instantiating it when it’s required.

image

  • The image proxy creates the real image only when the document editor asks it to display itself by invoking its Draw operation.
  • The proxy forwards subsequent requests directly to the image.
  • It must therefore keep a reference to the image after creating it.

Illustration: example Document Editor

image

Solution

Design a surrogate, or proxy, object that: instantiates the real object the first time the client makes a request of the proxy, remembers the identity of this real object, and forwards the instigating request to this real object.

Then all subsequent requests are simply forwarded directly to the encapsulated real object.

Applicability

Proxy is applicable whenever there is a need for a more versatile or sophisticated reference to an object than a simple pointer. Here are several common situations in which the Proxy pattern is applicable:

  1. A remote proxy provides a local representative for an object in a different address space. NEXTSTEP uses the class NXProxy for this purpose.
  2. A virtual proxy creates expensive objects on demand. The Image-Proxy described in the Motivation in an example of such a proxy.
  3. A Protection proxy controls access to the original object. Protection proxies are useful when objects should have different access rights.
  4. A smart reference is a replacement for a bare pointer that performs additional actions when an object is accessed.

Typical uses include

  • counting the number of references to the real object so that it can be freed automatically when them are no more references (also called smart pointers).
  • loading a persistent object into memory when it’s first referenced.
  • checking that the real object is locked before it’s accessed to ensure that no other object can change it

Structure

image

Object diagram of a proxy structure at run-time:

image

 

Collaborations

Proxy forward requests to RealSubject when appropriate, depending on the kind of proxy

image

Consequences

The proxy pattern introduces a level of indirection when accessing an object. The additional indirection has many uses, depending on the kind of proxy:

  1. A remote proxy can hide the fact that an object resides in a different address space.
  2. A virtual proxy can perform optimizations such as creating an object on demand.
  3. Both protection proxies and smart references allow additional housekeeping tasks when an object is accessed.

Model

image

Design Pattern: Mediator

The Mediator defines an object that controls how a set of objects interact. Loose coupling between colleague objects is achieved by having colleagues communicate with the Mediator, rather than with each other. Many a times in projects communication between components are complex.Due to this the logic between components becomes very complex. Mediator Pattern helps the objects to communicate in a disassociated manner, which leads to minimizing complexity.

Say that you’ve got a four-page Web site that lets users browse a store and make purchases. As things stand, the user can move from page to page. But there’s a problem — the code in each page has to know when to jump to a new page as well as how to activate the new page. You’ve got a lot of possible connections and a lot of duplicate code in the various pages.

image

You can use a mediator here to encapsulate all the navigation code out of the separate pages and place it into a mediator object instead. From then on, each page just has to report any change of state to the mediator, and the mediator knows what page to send the user to.  You can build the mediator to deal with the internals of each page so the various pages don’t have to know the intimate details of the other pages (such as which methods to call). And when it’s time to modify the navigation code that takes users from page to page, that code is all collected in one place, so
it’s easier to modify.

image

Illustration: Problem

Consider the implementation of dialog boxes in a GUI.  A dialog box uses a window to present a collection of widgets such as buttons, menus, and entry fields, as shown here.

image

Often there are dependencies between the widgets in the dialog. For example a button gets disabled or enabled when a certain entry in a list of choices of list box is selected .

Different dialog boxes will have different dependencies between widgets. So even though dialogs display the same kinds of widgets, they can’t simply reuse stock widget classes; they have to be customized to reflect dialog-specific dependencies. Customizing them individually by subclassing will be tedious, since many classes are involved.

Illustration:Solution

We can avoid previous said problem by encapsulating collective behavior in a separate mediator object. A mediator is responsible for controlling and coordinating the iterations of a group of objects. The mediator serves as an intermediary that keeps objects in the group form referring to each other explicitly. The objects only know the mediator, thereby reducing the number of interconnection

image

FontDialogDirector can be mediator between the widgets in a dialog box.

A FontDialogDirector object knows the widgets in a dialog and coordinates their interaction.

It acts as a hub of communication for widgets

 

image

In the above model notice who the director communicates with list box and entry field. Widgets communicate with each other only indirectly, through the director. All they know is the director and they in turn don’t know each other.

Furthermore, because the behavior is localized in one class, it can be changed or replaced by extending or replacing that class

Here’s the succession of events by which a list box’s selection passes to an entry field:

The following interaction diagram illustrates how the objects cooperate to handle a change in a list box’s selection.

image

1. The list box tells its director that it’s changed

2. The director gets the selection form the list box

3. The director passes the selection to the entry field

4. Now that the entry field contains some text, the director enables button(s) for initializing an action ( e.g. ‘demibold’,’oblique’

Applicability

Use the Mediator pattern when:

  1. a set of objects communicate in well-defined but complex ways . The resulting interdependencies are unstructured and difficult to understand.
  2. reusing an object is difficult because it refers to and communicates with many other objects.
  3. a behavior that’s distributed between several classes should be customizable without a lot of sub classing.

image

image

 

Collaborations

Colleagues send and receive requests form a Mediator object. The mediator implements the cooperative behavior by routing between the appropriate colleague(s).

Consequences

  1. It limits subclassing: mediator localizes behavior that otherwise would be distribured among various objects. Changing this behavior requires subclassing Mediator only; Colleagure classes can be reused as it is.
  2. It decouples colleagues:
  3. It simplifies object protocols: A one to many relationships are easier to understand, maintain, and extend. Thus mediator replaces many to many interactions with one-to-many interactions between the mediator and its colleagues.
  4. It abstracts how objects cooperate:
  5. It centralizes control:

Wednesday, April 6, 2011

Design Pattern : Command

The Command pattern allows requests to be encapsulated as objects, thereby allowing clients to be parameterized with different requests, queue or log requests, and support undoable operations.It falls into Behavioral category.

Illustration: - Menus implemented using command

  • Each choice in a Menu is an instance of a MenuItem class. An Application class creates these menus and their menu items along with the rest of the user interface. The Application class also keeps track of Document objects that a user has opened.
  • The application configures each MenuItem with an instance of a concrete Command subclass. When the user selects a Menuitem, the Menuitem calls Execute on its command, and Execute carries out the operation.
  • MenuItems don’t know which subclass of Command they use. Command subclasses store the receiver of the request and invoke one or more operations on the receiver.
  • For example, PasteCommand supports pasting text from the clipboard into a Document. PasteCommand’s receiver is the Document object it is supplied upon instantiation. The Execute operation invokes Paste on the receiving Document.
  • OpenCommand’s Execute operation is different: it prompts the user for a document name, creates a corresponding Document object, adds the document to the receiving application, and opens the document.
image imageimage

In each of these examples, notice how the Command pattern decouples the object that invokes the operation from the one having the knowledge to perform it. This gives us a lot of flexibility in designing our user interface. An application can provide both a menu and a push button interface to a feature just by making the menu and the push button share an instance of the same concrete Command subclass. We can replace commands dynamically, which would be useful for implementing context-sensitive menus. We can also support command scripting by composing commands into larger ones. All of this is possible because the object that issues a request only needs to know how to issue it; it doesn’t need to know how the request will be carried out.

Solution

  • Command decouples the object that invokes the operation from the one that knows how to perform it. To achieve this separation, the designer creates an abstract base class that maps a receiver (an object) with an action (a pointer to a member function). The base class contains an execute() method that simply calls the action on the receiver.
  • All clients of Command objects treat each object as a "black box" by simply invoking the object's virtual execute() method whenever the client requires the object's "service".
  • Sequences of Command objects can be assembled into composite (or macro) commands.

Applicability

Use the Command pattern when you want to

  • parameterize objects by an action to perform, as MenuItem.
  • You can express such parameterization in a procedural language with a callback function, that is, a function that’s registered somewhere to be called at a later point. Commands are an object Oriented replacement for callbacks.
  • Specify, queue, and execute requests at different times. A Command object can have a lifetime independent of the original request. If the receiver of a request can be represented in an address space-independent way, then you can transfer a command object for the request to a different process and fulfill the request there.
  • Supports Undo
  • Support logging changes to that they can be reapplied in case of a system crash. - Recovering form a crash involves reloading logged commands form disk and re-executing them with the execute operation.
  • Structure a system around high-level operations built on primitives operations. Such structure is common in information system that support transactions.

Structure

image

Collaborations

  • The client creates a ConcreteCommand object and specifies its receiver.
  • An Invoker object stores the ConcreteCommand object.
  • The invoker issues a request by calling Execute on the command. When commands are undo-able, ConcreteCommand stores state for undoing the com-mand prior to invoking Execute.
  • The ConcreteCommand object invokes operations on its receiver to carry out the request.

The following diagram shows the interactions between these objects. It illustrates how Command decouples the invoker form the receiver ( and the request it carries out ).

image

Consequences

The Command pattern has the following consequences:

  1. Command decouples the object that invokes the operation from the one that knows how to perform it.
  2. Commands are first-class objects. They can be manipulated and extended like any other object.
  3. You can assemble commands into a composite command. An example is the Macro Command class described earlier. In general, composite commands are an instance of the Composite pattern.
  4. It’s easy to add new Commands, because you don’t have to change existing classes

Model:

image

Tuesday, April 5, 2011

Design Pattern: Adapter

It falls into structural pattern category. The Adapter pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

imageimage

image

•Use the Adapter pattern when

  • You want to use an existing class, and its interface does not match the one you need.
  • You want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don’t necessarily have compatible interfaces.
  • You need to use several existing subclasses, but it’s impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class.

Structure

image

Collaborations

Clients call operations on an Adapter instance. In turn, the adapter calls Adaptee operations that carry out the request.

Consequences:

Class and object adapters have different trade-offs.

A: class adapter:

1. Adapts Adapter to target by committing to a concrete Adapter class. As a consequence, a class adapter won’t work when we want to adapt a class and all its subclasses.

2. Lets-adapter override some of Adaptee’s behavior, since Adapter is a subclass of Adaptee.

3. Introduces only one object, and no additional pointer indirection is needed to get to the Adaptee

B: Object adapter:

1.Lets a single adapter work with many Adaptees-that is, the Adaptee itself and all of its subclasses (if any). The Adapter can also add functionality to all Adaptees at once.

2. Makes it harder to overide Adaptee behavior. It will require subclassing Adaptee and making Adapter refer to the subclass rather than the Adapter itself.

Issues to be considered while using adapter pattern:

1. How much adapting does Adapter do?

  • Pluggable adapters.
  • Using two-way adapters to provide transparency

Design Pattern : Facade

It falls into structural pattern categories. The Facade Pattern defines a higher level interface to a subsystem, that makes it easier to use. It provides unified interface to a set of interfaces in a subsystem.

Use the Facade pattern when

•You want to provide a simple interface to a complex subsystem.

To tackle the complexity of subsystem as they evolve

Most patterns, when applied, result in more and smaller classes. This makes the subsystem more reusable and easier to customize, but it also becomes harder to use for clients that don’t need to customize it.

A façade can provide a simple default view of the subsystem that is good enough for most of the clients. Only clients needing more customizability will need to look beyond the façade

•Facade to decouple the subsystem for clients and other subsystems, thereby promoting subsystem independence and portability which tackle the disadvantage of dependencies between clients and the implementation classes on an abstraction.

•To layer your subsystem. Use façade to define an entry point to each subsystem level. If subsystems are dependent, then you can simplify the dependencies between them by making them communicate with each other solely through their facades.

The structure of the Façade Pattern looks as below

Picture3

•Clients communicate with the subsystem by sending request to Façade, which forwards them to the appropriate subsystem object(s). Although the subsystem objects perform the actual work, the façade may have to do work of its own to translate its interface to subsystem interfaces.

•Clients that user the façade don’t have to access its subsystem objects directly.

The Facade Patterns offers the following benefits:

•1. It shields client from subsystem components, thereby reducing the number of objects that clients deal with and making the subsystem easier to use.

•It promotes weak coupling between the subsystem and its clients.

•It doesn’t prevent applications form using subsystem classes if they need to. Thus you can choose between ease of use and generality

Illustration: Problem

Consider for example a programming environment that gives application access to its compiler subsystem. This subsystem contains classes such as Scanner, Parser,ProgramNode, ByteCodeStream, and ProgramNodeBuilder that implements the Compiler. Some Specialized applications might need to access these classes directly.

But most clients of a compiler generally don’t care about details like parsing and byte code generation; they merely want to complier subsysem only complicate their task.

Illustration : solution

Picture4

Compiler class in the above can act as a facade, which will provide higher-level interface that can shield clients form these classes, the compiler subsystem also includes a Compiler class. This class defines a unified interface to the compiler’s functionality.

It offers client a single, simple interface to the compiler subsystem. It glues together the classes that implement compiler functionality without hiding them completely.

[Compiler façade makes easier for most programmers without hiding the lower-level functionality form the few that need it]

Class Diagram Solution:

image