Showing posts with label Behavioral. Show all posts
Showing posts with label Behavioral. Show all posts

Thursday, 6 August 2015

The State Pattern

The State Pattern


Defined

The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.

Encapsulates state-based behavior and delegate behavior to current state

Diagrams



Code Examples

 


 


Bullet Points

  • The State Pattern allows an object to have many different behaviors that are base on its internal state.
  •  Unlike a procedural state machine, the State Pattern represents state as a full blown class.
  • The Context gets its behavior by delegating to the current state object it is composed with.
  • By encapsulating each state into a class, we localize any changes that will need to be made.
  • The State and Strategy Patterns have the same class diagram, but they differ in intent.
  • Strategy Patterns typically configures Context classes with a behavior or algorithm.
  • State Pattern allows a Context to change its behavior as the state of the Context changes.
  • State transitions can be controlled by the State classes  or by the context classes.
  • Using the State patter will typically result in a great number of classes in your design.
  • State classes may be shared among Context instances.

Tuesday, 4 August 2015

The Iterator Pattern

 The Iterator Pattern

Defined

The Iterator Pattern provides a way to access the elements of an aggregate sequentially without exposing its underlying representation.

Diagram




Code Example

Below is a code example of how to allow a client  to iterate through a collection,  without  caring about if the collection is an array or a list etc, and to do all of this without having to modify the client code, i.e if another collection type of an object presents itself, client code doesn't need changing. Open-closed principle ;)

 public interface IIterator
{
  bool HasNext();
  object Next();
}

public abstract class CatenatedStringInterator : IIterator
{
   protected string _theStringToIterateOver;
   protected int lastSubstringPoint = 0;
  
   public abstract bool HasNext();
   public abstract object Next();
  
}

public class CommaSeperatedStringInterator : CatenatedStringInterator
{
 

    public CommaSeperatedStringInterator(string theStringToIterateOver)
    {
       _theStringToIterateOver = theStringToIterateOver;
    }

     public override bool HasNext()
    {
       //Check if there is a next string by looking for commas
    }
   
    public override object Next()
    {
       //get next string
    }
}

public class AstrixSeperatedStringInterator : CatenatedStringInterator
{
    private string _theStringToIterateOver;
    private int lastSubstringPoint = 0;

    public AstrixSeperatedStringInterator(string theStringToIterateOver)
    {
       _theStringToIterateOver = theStringToIterateOver;
    }

     public override  bool HasNext()
    {
       //Check if there is a next string by looking for Astrixes
    }
   
    public override object Next()
    {
       //get next string
    }
}

public class CatenatedStringPrinter
{
     public void PrintStringsInFile(IIterator iterator)
      {
   
       if (iterator.HasNext())
      {
          System.Print((String)iterator.Next());
       }
   }
}


Bullet Points 

  •  An iterator allows access to an aggregates elements without exposing its internal structure.
  • An Iterator takes the job of iterating over an aggregate an encapsulates it in another object.
  • When using an Iterator, we relieve the aggregate of the responsibility of supporting operations for traversing its data.
  • An Iterator provides a common interface for traversing the items of an aggregate, allowing you to use polymorphism when writing code that makes use of the items of the aggregate.
  • We should strive to assign only one responsibility to each class.

Monday, 3 August 2015

The Template Method Pattern

The Template Method Pattern



Defined

The template method defines the skeleton of an algorithm within a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changes the algorithm structure.

The Template Method Defines steps of an algorithm and allows subclasses to provided the implementation of on or more steps.

Diagrams

Code Example

example of a normal template method

 example of a template method with a hook


A hook is a method that is declared in the abstract class, but only given an empty or default implementation. This gives subclasses the ability to "hook into" the algorithm at various points, if they wish; a subclass is also free to ignore the hook.


The use the hook, we override it in our subclass.

Bullet Points

  •  The "template method" defines the steps of an algorithm, deferring to subclasses for the implementation of those steps. 
  • The Template Method Patter gives us an important technique for code re-use.
  • The Template Methods abstract class may define concrete method, abstract methods and hooks.
  •  Abstract method are implemented by subclasses.
  • Hooks are methods that do nothing or default behavior in the abstract class, but may be overridden in subclasses. 
  • To prevent subclasses from changing the algorithm in the template method, declare the template method as final. 
  • The Hollywood Principle guides use to put decisions making in high-level modules that can decide how and when to call low level modules. 
  • You'll see lots of uses of the Template Method Pattern in real world code, but don't expect it all (like any Pattern) to be designed by the book. 
  • The Strategy and Template Method Patterns both encapsulate algorithms, one by inheritance and one by composition. 
  • The Factory Method is a specialization of Template Method. 


 

Monday, 27 July 2015

The Command Pattern

The Command Pattern


Defined

 The Command Pattern encapsulates a request as an object, thereby letting you parametrize other objects with different requests, ques or log request and support undo-able operations.

- A command object encapsulates a request, by binding together a set of actions on a specific receiver. To achieve this, it packages the actions and the receiver up into an object that exposes just one method, execute(). When called, execute() causes the actions to be invoked on the receiver,From the outside, no other objects really know what actions get performed on what receiver, they just know that if they call the execute method their request will be serviced.


Diagrams




Code Examples







Macro Commands
- A Kind of command that can execute other commands... and more then one of them.


Bullet Points

  • The Command Pattern decouples an object, making a request from the one that knows how to perform it.
  • A Command object is at the center of this decoupling and encapsulates a receiver with an action (or set of actions).
  • An invoker makes a request of a Command object by calling its execute() method, which invokes those actions on the receiver.
  •  Invokers can be parametrized with Commands, even dynamically at run-time.
  • Commands may support undo by implementing an undo method that restores the object to its previous state before the execute() method was last called.
  • Macro Commands are a simple extension of Command that allow multiple commands to be invoked. likewise Macro Commands can easily support undo().
  • In practice, it is not uncommon for "smart" Command Objects to implement the request themselves rather than delegating to a receiver.
  • Commands may also be used to implement logging and transaction systems.

Tuesday, 5 May 2015

Observer Pattern

 Observer pattern

 

Defined

The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

When you're trying to picture the Observer Pattern, a newspaper subscription service with its publishers and subscribers is a good way to visualize the pattern.

In the real world however, you'll typically see the Observer Pattern defined like this.

The subject (the observed object) and the observers define the one to many relationship.
The observers are dependent on the subject such that when the subjects state changes, the observers are updated with new values.


 Strive for Loose coupled design between objects that interact.


Loose coupling is an approach to interconnecting the components in a system or network so that those components, also called elements, depend on each other to the least extent practicable. Coupling refers to the degree of direct knowledge that one element has of another.

The goal of a loose coupling architecture is to reduce the risk that a change made within one element will create unanticipated changes within other elements.Don't wish to code concrete update method implementations, as we have to way of add or remove without making changes to the program.

Diagrams

 




Code Example


 




 

 





Bullet Points

  • The Observer Pattern defines a one to many relationship between objects.
  • Subjects, or as we also know them, Observables, update Observers using common interface.
  • Observers are loosely coupled in that the Observable knows nothing about them, other than that they implement the observer Interface.
  • You can push or pull data from the Observable when using the pattern (pull us considered correct)
  • Dont depend on a specific order of notification for your observers.


Friday, 1 May 2015

Strategy pattern

Strategy pattern 

Defined

Defines a family of algorithms, encapsulates each one, and makes them interchangeable.
The Strategy Pattern lets the algorithm vary independently from clients that use it,

Use when client of inherited base class may have varying behaviors and dependent of scenario you may want to use one or the other interchangeably.

Identify the aspects of your application that vary and separate them from what stays the same.
Take what varies and "encapsulate" it so it wont affect the rest of your code.

Diagrams


Code Example



i.e a CARs Exhaust Noise varys dependent of what type of Car your driving



interface IExhaustNoiseBehavior()
{
   private string noise;

    public string Noise()
}

class SportsCarExhaustNoiseBehavior :  IExhaustNoise
{
    private string noise = "brrrrm"
 
    public string Noise
    {
      return noise;
     }
}


public class Car
{
    IExhaustNoiseBehavior exhaustNoiseBehavior
      public performExhaustNoise() {  return ExhaustNoiseBehavior.Noise };

}

public class  Ferrari : Car
{

     IExhaustNoise ExhaustNoise
 
      public Ferrari ( IExhaustNoise exhaustNoiseBehavior)
      {
         ExhaustNoise =  new SportsCarExhaustNoiseBehavior();
       }
}

Bullet Points


  • defines a family of algorithms,

  • encapsulates each algorithm, and
  • makes the algorithms interchangeable within that family