Friday, 7 August 2015

The Proxy Pattern

The Proxy Pattern

Defined

The Proxy Pattern provides a surrogate or placeholder for another object to control access to it.

Diagram


Bullet Points

  • The Proxy Pattern provides a representative for another object in order to control the clients access to it. There re a number of ways it can manage that access. 
  • A Remote Proxy manages interaction between a client and a remote object.
  • A Virtual Proxy controls access to an object that is expensive to initiate.
  • A Protection Proxy control access to the methods of an object base on the caller.
  • Many other variants of the Proxy Pattern exist including catching proxies, synchronization proxies, firewall proxies, 
  • Proxy is structurally similar to Decorator, but the two differ in purpose.
  • The Decorator Pattern adds behavior to an object, while a Proxy controls access.
  • Like any wrapper, proxies will increase the Sumner of classes and objects in your design.

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.

Wednesday, 5 August 2015

The Composite Pattern

 The Composite Pattern

 Defined

The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uni-formally.

The Composite Pattern allows use to build structures of objects in the form of trees that contain both compositions of objects and individual objects as nodes.

Using a composite structure, we can apply the same operations over both composites and individual objects, in other words, in most cases we can ignore the difference between compositions of objects and individual objects.



Lets think about composition in terms of menus: this pattern gives us a way to create a tree structure that can handle a nested group of menus and menu items in the same structure. By putting menus and items in the same structure we create a part-whole hierarchy; that is, a tree of objects that made of parts(menus and menu items) but that can be treated as a whole, like on big uber menu.


Once we have our uber menu, we can use this pattern to treat "individual objects and compositions uniformly".
What does that mean? it means if we have a tree structure of menus, sub menus, and perhaps subsubmenus with menu items, then any menu is a "composition" because it can constrains both other menus and menu items, The individual objects are just the menu items, they don't hold other objects,

A composite contains components, components come in two flavors: composites and leaf elements A composite holds a set of children, those children may be other composites or leaf elements.

Diagrams

Tree Structure

Pattern Structure






Diagram shows example how we can tree like structure, where a menu can compose of menu items, and other menus that can contain their own menu items or menus.

 

 

Code Example






 

Bullet Points

  • The Composite Pattern provides a structure to hold both individual objects and composites.
  • The Composite Pattern allows clients to treat composites and individual objects uniformly.
  • A Component is any object in a Composite structure. Components may be other composites or leaf nodes.
  • There are many design trade offs in implementing Composite. You need to balance transparency and safety with your needs.

Single Responsibility Principle

Single Responsibility Principle - Class should only have one reason to change

When we allow a class to not only take care of its own business (managing some kind of aggregate) but also take on more responsibilities. then we've given the class two reasons to change.

We know we want to avoid change in a class like the plague; as modifying code provides all sorts of opportunities for problems to creep in. Having two ways to change increase the probability that class will change in the future and when it does, its going to affect two aspects

Every responsibility of a class is an area of potential change. More than one responsibility means more than one area of change.
The Principle guides us to assign responsibility to one class and only one class.

Separating responsibility is one of the hardest things to do. The only way to succeed is to be diligent in examining your designs and to watch out for signals that a class is changing in more than one way as your system grows.


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.

The Hollywood Principle (Dont call us, we'll call you)

The Hollywood Principle (Don't call us, we'll call you)

Gives us a way to prevent dependency rot.
Dependency rot happens when you have high level components depending on low-level components depending on high-level components depending on side-way components depending on low-level components and so on.

With the Hollywood principle,  we allow low-level components to hook themselves into a system, but the high-level components determine when they are needed, and how. in other words, the high-level components give the low level components the "Don't call use, we'll call you" treatment.


The connection between the template design method and the Hollywood Principle is somewhat app-rant. Considering it is the abstract class (the higher level component) that calls the Subclasses implementations of its abstract methods.

Subclasses (low level components) never call abstract classes (high level components) without being called first.


Q: is a low level component disallowed from calling a method in a high-level component?

A Not really, IN, fact a low level component will often end up calling a member defined above in its inheritance hierarchy purely through inheritance. But we want to avoid creating explicit circular dependencies between the low-level component and the high-level ones.




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.