Wednesday, July 18, 2012

Design Patterns Applicability

copyright from: www.dsoftworld.com


Creational Patterns

Abstract factory (Kit)

Use the Abstract Factory pattern when

o A system should be independent of how its products are created, composed, and represented.

o A system should be configured with one of multiple families of products.

o A family of related product objects is designed to be used together, and you need to enforce this constraint.

o You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

Builder

Use the Builder pattern when

o The algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled.

o The construction process must allow different representations for the object that's constructed.

Factory Method (virtual constructor)

Use the Factory Method pattern when

o A class can't anticipate the class of objects it must create.
o A class wants its subclasses to specify the objects it creates.
o Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.


Prototype

Use the Prototype pattern when

o a system should be independent of how its products are created, composed, and represented; 

and

o when the classes to instantiate are specified at run-time, for example, by dynamic loading; 

or

o to avoid building a class hierarchy of factories that parallels the class hierarchy of products; or

o When instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state.

Singleton

Use the Singleton pattern when

o There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
o When the sole instance should be extensible by sub classing, and clients should be able to use an extended instance without modifying their code.


Structural Patterns

Adapter (Wrapper)

Use the Adapter pattern when

o You want to use an existing class, and its interface does not match the one you need.

o You want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces.

o (Object adapter only) 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.


Bridge (Handle/Body)

Use the Bridge pattern when

o You want to avoid a permanent binding between an abstraction and its implementation. This might be the case, for example, when the implementation must be selected or switched at run-time.

o Both the abstractions and their implementations should be extensible by subclassing. In this case, the Bridge pattern lets you combine the different abstractions and implementations and extend them independently.

o Changes in the implementation of an abstraction should have no impact on clients; that is, their code should not have to be recompiled.

o (C++) you want to hide the implementation of an abstraction completely from clients. In C++ the representation of a class is visible in the class interface.

o You have a proliferation of classes as shown earlier in the first Motivation diagram. Such a class hierarchy indicates the need for splitting an object into two parts. Rumbaugh uses the term "nested generalizations"

o To refer to such class hierarchies.

o You want to share an implementation among multiple objects (perhaps using reference counting), and this fact should be hidden from the client.


Composite

Use the Composite pattern when

o you want to represent part-whole hierarchies of objects.

o you want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly.

Decorator (Wrapper)

Use Decorator

o To add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.

o For responsibilities that can be withdrawn.

o When extension by subclassing is impractical. Sometimes a large number of independent extensions are

o Possible and would produce an explosion of subclasses to support every combination. Or a class definition

o May be hidden or otherwise unavailable for subclassing.

Façade

Use the Facade pattern when

o You want to provide a simple interface to a complex subsystem. Subsystems often get more complex as they

o Evolve. Most patterns, when applied, result in more and smaller classes. This makes the subsystem more

o Reusable and easier to customize, but it also becomes harder to use for clients that don't need to customize it. A

o Facade can provide a simple default view of the subsystem that is good enough for most clients. Only clients

o Needing more customizability will need to look beyond the facade.

o There are many dependencies between clients and the implementation classes of an abstraction. Introduce a

o facade to decouple the subsystem from clients and other subsystems, thereby promoting subsystem independence and portability.

o You want to layer your subsystems. Use a facade 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.

FlyWeight

The Flyweight pattern's effectiveness depends heavily on how and where it's used. Apply the Flyweight pattern when all of the following are true:

o An application uses a large number of objects.

o Storage costs are high because of the sheer quantity of objects.

o Most object state can be made extrinsic.

o Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed.

o The application doesn't depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects.

Proxy (Surrogate)

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:

o A remote proxy provides a local representative for an object in a different address space. Coplien calls this kind of proxy an "Ambassador."

o A virtual proxy creates expensive objects on demand.

o A protection proxy controls access to the original object. Protection proxies are useful when objects should have different access rights. For example, KernelProxies in the Choices operating system provide protected access to operating system objects.

o 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 there are no more references (also called smart pointers).

o Loading a persistent object into memory when it's first referenced.

o Checking that the real object is locked before it's accessed to ensure that no other object can change it.


Behavioral Patterns

Chain of responsibility

Use Chain of Responsibility when

o More than one object may handle a request, and the handler isn't known a priori. The handler should be ascertained automatically.

o You want to issue a request to one of several objects without specifying the receiver explicitly the set of objects that can handle a request should be specified dynamically.

Command (Action, Transaction)
Use the Command pattern when

o You want to parameterize objects by an action to perform, as MenuItem objects did above. 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.

o 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 spaceindependent way, then you can transfer a command object for the request to a different process and fulfill the request there.

o Support undo. The Command's Execute operation can store state for reversing its effects in the command itself. The Command interface must have an added Unexecute operation that reverses the effects of a previous call to Execute. Executed commands are stored in a history list. Unlimited-level undo and redo is achieved by traversing this list backwards and forwards calling Unexecute and Execute, respectively.

o Support logging changes so that they can be reapplied in case of a system crash. By augmenting the Command interface with load and store operations, you can keep a persistent log of changes.

o Recovering from a crash involves reloading logged commands from disk and reexecuting them with the Execute operation.

o Structure a system around high-level operations built on primitives operations. Such a structure is common in information systems that support transactions. A transaction encapsulates a set of changes to data. The Command pattern offers a way to model transactions. Commands have a common interface, letting you invoke all transactions the same way. The pattern also makes it easy to extend the system with new transactions.

Interpreter

Use the Interpreter pattern when there is a language to interpret, and you can represent statements in the language as abstract syntax trees. The Interpreter pattern works best when

o The grammar is simple. For complex grammars, the class hierarchy for the grammar becomes large and unmanageable. Tools such as parser generators are a better alternative in such cases.

o They can interpret expressions without building abstract syntax trees, which can save space and possibly time.

o Efficiency is not a critical concern. The most efficient interpreters are usually not implemented by interpreting parse trees directly but by first translating them into another form. For example, regular expressions are often transformed into state machines. But even then, the translator can be implemented by the Interpreter pattern, so the pattern is still applicable.

Iterator (Cursor)

Use the Iterator pattern

o To access an aggregate object's contents without exposing its internal representation.

o To support multiple traversals of aggregate objects.

o To provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration).

Mediator

Use the Mediator pattern when

o a set of objects communicate in well-defined but complex ways. The resulting interdependencies are unstructured and difficult to understand.

o reusing an object is difficult because it refers to and communicates with many other objects.

o a behavior that's distributed between several classes should be customizable without a lot of subclassing.

Memento (Token)

Use the Memento pattern when

o A snapshot of (some portion of) an object's state must be saved so that it can be restored to that state later, and

o A direct interface to obtaining the state would expose implementation details and break the object's encapsulation.

Observer (Dependents, Publish-Subscribe)

Use the Observer pattern in any of the following situations:

o When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.

o When a change to one object requires changing others, and you don't know how many objects need to be changed.

o 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.

State (Objects for States)

Use the State pattern in either of the following cases:

o An object's behavior depends on its state, and it must change its behavior at run-time depending on that state.

o Operations have large, multipart conditional statements that depend on the object's state. This state is usually represented by one or more enumerated constants. Often, several operations will contain this same conditional structure. The State pattern puts each branch of the conditional in a separate class. This lets you treat the object's state as an object in its own right that can vary independently from other objects.

Strategy (Policy)

Use the Strategy pattern when

o Many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many behaviors.

o You need different variants of an algorithm. For example, you might define algorithms reflecting different space/time trade-offs. Strategies can be used when these variants are implemented as a class hierarchy of algorithms

o An algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures.

o A class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class.

Template Method

The Template Method pattern should be used

o To implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary.

o When common behavior among subclasses should be factored and localized in a common class to avoid code duplication. This is a good example of "refactoring to generalize" as described by Opdyke and Johnson. You first identify the differences in the existing code and then separate the differences into new operations. Finally, you replace the differing code with a template method that calls one of these new operations.

o To control subclasses extensions. You can define a template method that calls "hook" operations at specific points, thereby permitting extensions only at those points

Visitor

Use the Visitor pattern when

o An object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes.

o Many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid "polluting" their classes with these operations. Visitor lets you keep related operations together by defining them in one class. When the object structure is shared by many applications, use Visitor to put operations in just those applications that need them.

o The classes defining the object structure rarely change, but you often want to define new operations over the structure. Changing the object structure classes requires redefining the interface to all visitors, which is potentially costly. If the object structure classes change often, then it's probably better to define the operations in those classes.

reference:
Design Patterns: Elements of Reusable Object-Oriented Software book

No comments: