Tuesday, November 20, 2012

Memento pattern




  • Memento Design Pattern


Intent

    Without violating encapsulation, capture and externalize an object’s internal state so that the object can be returned to this state later.
    A magic cookie that encapsulates a “check point” capability.
    Promote undo or rollback to full object status.


Rules of thumb


    Command and Memento act as magic tokens to be passed around and invoked at a later time. In Command, the token represents a request; in Memento, it represents the internal state of an object at a particular time. Polymorphism is important to Command, but not to Memento because its interface is so narrow that a memento can only be passed as a value.
    Command can use Memento to maintain the state required for an undo operation.
    Memento is often used in conjunction with Iterator. An Iterator can use a Memento to capture the state of an iteration. The Iterator stores the Memento internally.
http://sourcemaking.com/design_patterns/memento




  • Memento pattern


The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).

The memento pattern is implemented with two objects: the originator and a caretaker. The originator is some object that has an internal state. The caretaker is going to do something to the originator, but wants to be able to undo the change. The caretaker first asks the originator for a memento object. Then it does whatever operation (or sequence of operations) it was going to do. To roll back to the state before the operations, it returns the memento object to the originator. The memento object itself is an opaque object (one which the caretaker cannot, or should not, change). When using this pattern, care should be taken if the originator may change other objects or resources - the memento pattern operates on a single object.

Classic examples of the memento pattern include the seed of a pseudorandom number generator (it will always produce the same sequence thereafter when initialized with the seed state) and the state in a finite state machine.

http://en.wikipedia.org/wiki/Memento_pattern

Template Method Pattern



  • Template Method Design Pattern

Intent

    Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

Rules of thumb

    Strategy is like Template Method except in its granularity.
    Template Method uses inheritance to vary part of an algorithm. Strategy uses delegation to vary the entire algorithm.
    Strategy modifies the logic of individual objects. Template Method modifies the logic of an entire class.
    Factory Method is a specialization of Template Method.
http://sourcemaking.com/design_patterns/template_method



  • Template method pattern

 the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm's structure
 http://en.wikipedia.org/wiki/Template_method_pattern

State pattern



  • State Design Pattern


Intent

    Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
    An object-oriented state machine
    wrapper + polymorphic wrappee + collaboration


Example


The State pattern allows an object to change its behavior when its internal state changes. 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.


Rules of thumb

    State objects are often Singletons.
    Flyweight explains when and how State objects can be shared.
    Interpreter can use State to define parsing contexts.
    Strategy has 2 different implementations, the first is similar to State. The difference is in binding times (Strategy is a bind-once pattern, whereas State is more dynamic).
    The structure of State and Bridge are identical (except that Bridge admits hierarchies of envelope classes, whereas State allows only one). The two patterns use the same structure to solve different problems: State allows an object’s behavior to change along with its state, while Bridge’s intent is to decouple an abstraction from its implementation so that the two can vary independently.
    The implementation of the State pattern builds on the Strategy pattern. The difference between State and Strategy is in the intent. With Strategy, the choice of algorithm is fairly stable. With State, a change in the state of the “context” object causes it to select from its “palette” of Strategy objects.

http://sourcemaking.com/design_patterns/state




  • State pattern

The state pattern, which closely resembles Strategy Pattern, is a behavioral software design pattern, also known as the objects for states pattern. This pattern is used in computer programming to represent the state of an object. This is a clean way for an object to partially change its type at runtime
http://en.wikipedia.org/wiki/State_pattern

Null Object pattern



  • Null Object pattern

a Null Object is an object with defined neutral ("null") behavior.
The Null Object design pattern describes the uses of such objects and their behavior (or lack thereof).

Instead of using a null reference to convey absence of an object (for instance, a non-existent customer), one uses an object which implements the expected interface, but whose method body is empty. The advantage of this approach over a working default implementation is that a Null Object is very predictable and has no side effects: it does nothing.

For example, a function may retrieve a list of files in a directory and perform some action on each. In the case of an empty directory, one response may be to throw an exception or return a null reference rather than a list. Thus, the code which expects a list must verify that it in fact has one before continuing, which can complicate the design.

By returning a null object (i.e. an empty list) instead, there is no need to verify that the return value is in fact a list. The calling function may simply iterate the list as normal, effectively doing nothing. It is, however, still possible to check whether the return value is a null object (e.g. an empty list) and react differently if desired.

The null object pattern can also be used to act as a stub for testing if a certain feature, such as a database, is not available for testing.

http://en.wikipedia.org/wiki/Null_Object_pattern



  • Rules of thumb


    The Null Object class is often implemented as a Singleton. Since a null object usually does not have any state, its state can’t change, so multiple instances are identical. Rather than use multiple identical instances, the system can just use a single instance repeatedly.
    If some clients expect the null object to do nothing one way and some another, multiple NullObject classes will be required. If the do nothing behavior must be customized at run time, the NullObject class will require pluggable variables so that the client can specify how the null object should do nothing (see the discussion of pluggable adaptors in the Adapter pattern). This may generally be a symptom of the AbstractObject not having a well defined (semantic) interface.
    A Null Object does not transform to become a Real Object. If the object may decide to stop providing do nothing behavior and start providing real behavior, it is not a null object. It may be a real object with a do nothing mode, such as a controller which can switch in and out of read-only mode. If it is a single object which must mutate from a do nothing object to a real one, it should be implemented with the State pattern or perhaps the Proxy pattern. In this case a Null State may be used or the proxy may hold a Null Object.
    The use of a null object can be similar to that of a Proxy, but the two patterns have different purposes. A proxy provides a level of indirection when accessing a real subject, thus controlling access to the subject. A null collaborator does not hide a real object and control access to it, it replaces the real object. A proxy may eventually mutate to start acting like a real subject. A null object will not mutate to start providing real behavior, it will always provide do nothing behavior.
    A Null Object can be a special case of the Strategy pattern. Strategy specifies several ConcreteStrategy classes as different approaches for accomplishing a task. If one of those approaches is to consistently do nothing, that ConcreteStrategy is a NullObject. For example, a Controller is a View’s Strategy for handling input, and NoController is the Strategy that ignores all input.
    A Null Object can be a special case of the State pattern. Normally, each ConcreteState has some do nothing methods because they’re not appropriate for that state. In fact, a given method is often implemented to do something useful in most states but to do nothing in at least one state. If a particular ConcreteState implements most of its methods to do nothing or at least give null results, it becomes a do nothing state and as such is a null state.
    A Null Object can be used to allow a Visitor to safely visit a hierarchy and handle the null situation.
    Null Object is a concrete collaborator class that acts as the collaborator for a client which needs one. The null behavior is not designed to be mixed into an object that needs some do nothing behavior. It is designed for a class which delegates to a collaborator all of the behavior that may or may not be do nothing behavior
   
    http://sourcemaking.com/design_patterns/null_object

Mediator pattern



  • Mediator Design Pattern

Intent

    Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
    Design an intermediary to decouple many peers.
    Promote the many-to-many relationships between interacting peers to “full object status”.
   
Example

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

Rules of thumb

    Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple senders and receivers, but with different trade-offs. Chain of Responsibility passes a sender request along a chain of potential receivers. Command normally specifies a sender-receiver connection with a subclass. Mediator has senders and receivers reference each other indirectly. Observer defines a very decoupled interface that allows for multiple receivers to be configured at run-time.
    Mediator and Observer are competing patterns. The difference between them is that Observer distributes communication by introducing “observer” and “subject” objects, whereas a Mediator object encapsulates the communication between other objects. We’ve found it easier to make reusable Observers and Subjects than to make reusable Mediators.
    On the other hand, Mediator can leverage Observer for dynamically registering colleagues and communicating with them.
    Mediator is similar to Facade in that it abstracts functionality of existing classes. Mediator abstracts/centralizes arbitrary communication between colleague objects, it routinely “adds value”, and it is known/referenced by the colleague objects (i.e. it defines a multidirectional protocol). In contrast, Facade defines a simpler interface to a subsystem, it doesn’t add new functionality, and it is not known by the subsystem classes (i.e. it defines a unidirectional protocol where it makes requests of the subsystem classes but not vice versa).
http://sourcemaking.com/design_patterns/mediator



  • Mediator pattern

The mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program's running behavior.
http://en.wikipedia.org/wiki/Mediator_pattern

Interpreter Pattern


Interpreter Design Pattern

Intent

    Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
    Map a domain to a language, the language to a grammar, and the grammar to a hierarchical object-oriented design.

Rules of thumb
    Considered in its most general form (i.e. an operation distributed over a class hierarchy based on the Composite pattern), nearly every use of the Composite pattern will also contain the Interpreter pattern. But the Interpreter pattern should be reserved for those cases in which you want to think of this class hierarchy as defining a language.
    Interpreter can use State to define parsing contexts.
    The abstract syntax tree of Interpreter is a Composite (therefore Iterator and Visitor are also applicable).
    Terminal symbols within Interpreter’s abstract syntax tree can be shared with Flyweight.
    The pattern doesn’t address parsing. When the grammar is very complex, other techniques (such as a parser) are more appropriate.


http://sourcemaking.com/design_patterns/interpreter


Interpreter pattern
the interpreter pattern is a design pattern that specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence
http://en.wikipedia.org/wiki/Interpreter_pattern

Chain of Responsibility Pattern



  • Rules of thumb


    Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple senders and receivers, but with different trade-offs. Chain of Responsibility passes a sender request along a chain of potential receivers.
    Chain of Responsibility can use Command to represent requests as objects.
    Chain of Responsibility is often applied in conjunction with Composite. There, a component’s parent can act as its successor
http://sourcemaking.com/design_patterns/chain_of_responsibility



  • Chain-of-responsibility pattern

the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.
http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern