Showing posts with label Design Patterns-Creational patterns. Show all posts
Showing posts with label Design Patterns-Creational patterns. Show all posts

Monday, October 7, 2013

Lazy initialization

Lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.

This is typically accomplished by maintaining a flag indicating whether the process has taken place. Each time the desired object is summoned, the flag is tested. If it is ready, it is returned. If not, it is initialized on the spot. In multithreaded code, access to the flag must be synchronized to guard against a race condition.

See lazy evaluation for a general treatment of this idea. In heavily imperative languages this pattern carries hidden dangers, as does any programming habit that relies on shared state.

 Lazy<Fruit> lazyFruit = new Lazy<Fruit>();  
 Fruit fruit = lazyFruit.Value;  

Here is a dummy example in C#.
The Fruit class itself doesn't do anything here, The class variable _typesDictionary is a Dictionary/Map used to store Fruit instances by typeName.


 using System;  
 using System.Collections;  
 using System.Collections.Generic;  
 public class Fruit  
 {  
   private string _typeName;  
   private static Dictionary<string, Fruit> _typesDictionary = new Dictionary<string, Fruit>();  
   private Fruit(String typeName)  
   {  
     this._typeName = typeName;  
   }  
   public static Fruit GetFruitByTypeName(string type)  
   {  
     Fruit fruit;  
     if (!_typesDictionary.TryGetValue(type, out fruit))  
     {  
       // Lazy initialization  
       fruit = new Fruit(type);  
       _typesDictionary.Add(type, fruit);  
     }  
     return fruit;  
   }  
   public static void ShowAll()  
   {  
     if (_typesDictionary.Count > 0)  
     {  
       Console.WriteLine("Number of instances made = {0}", _typesDictionary.Count);  
       foreach (KeyValuePair<string, Fruit> kvp in _typesDictionary)  
       {  
         Console.WriteLine(kvp.Key);  
       }  
       Console.WriteLine();  
     }  
   }  
   public Fruit()  
   {  
     // required so the sample compiles  
   }  
 }  
 class Program  
 {  
   static void Main(string[] args)  
   {  
     Fruit.GetFruitByTypeName("Banana");  
     Fruit.ShowAll();  
     Fruit.GetFruitByTypeName("Apple");  
     Fruit.ShowAll();  
     // returns pre-existing instance from first   
     // time Fruit with "Banana" was created  
     Fruit.GetFruitByTypeName("Banana");  
     Fruit.ShowAll();  
     Console.ReadLine();  
   }  
 }  


 

Multiton pattern

The multiton pattern is a design pattern similar to the singleton, which allows only one instance of a class to be created. The multiton pattern expands on the singleton concept to manage a map of named instances as key-value pairs.

Rather than have a single instance per application (e.g. the java.lang.Runtime object in the Java programming language) the multiton pattern instead ensures a single instance per key.

using System.Collections.Generic;  
 namespace MyApplication {  
   class FooMultiton {  
     private static readonly Dictionary<object, FooMultiton> _instances = new Dictionary<object, FooMultiton>();  
     private FooMultiton() {  
     }  
     public static FooMultiton GetInstance(object key) {  
       lock (_instances) {    
         FooMultiton instance;  
         if (!_instances.TryGetValue(key, out instance)) {  
           instance = new FooMultiton();  
           _instances.Add(key, instance);  
         }  
         return instance;  
       }  
     }  
   }  
 }  

Friday, September 20, 2013

Builder pattern

Title:
 Builder pattern

Definition:
The intent of the Builder design pattern is to separate the construction of a complex object from its representation. By doing so, the same construction process can create different representations.



Builder:
Builder is responsible for defining the construction process for individual
parts. Builder has those individual processes to initialize and
configure the product.

Director: 
Director takes those individual processes from the builder and
defines the sequence to build the product.

Product: 
Product is the final object which is produced from the builder
and director coordination.


Java:










Check list


  1. Decide if a common input and many possible representations (or outputs) is the problem at hand.
  2. Encapsulate the parsing of the common input in a Reader class.
  3. Design a standard protocol for creating all possible output representations. Capture the steps of this protocol in a Builder interface.
  4. Define a Builder derived class for each target representation.
  5. The client creates a Reader object and a Builder object, and registers the latter with the former.
  6. The client asks the Reader to “construct”.
  7. The client asks the Builder to return the result.

Rules of thumb


  • Sometimes creational patterns are complementory: Builder can use one of the other patterns to implement which components get built. Abstract Factory, Builder, and Prototype can use Singleton in their implementations.
  • Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
  • Builder often builds a Composite.
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.

Code Example:

using System;
using System.Collections;

  public class MainApp
  {
    public static void Main()
    { 
      // Create director and builders 
      Director director = new Director();

      Builder b1 = new ConcreteBuilder1();
      Builder b2 = new ConcreteBuilder2();

      // Construct two products 
      director.Construct(b1);
      Product p1 = b1.GetResult();
      p1.Show();

      director.Construct(b2);
      Product p2 = b2.GetResult();
      p2.Show();

      // Wait for user 
      Console.Read();
    }
  }

  // "Director" 
  class Director
  {
    // Builder uses a complex series of steps 
    public void Construct(Builder builder)
    {
      builder.BuildPartA();
      builder.BuildPartB();
    }
  }

  // "Builder" 
  abstract class Builder
  {
    public abstract void BuildPartA();
    public abstract void BuildPartB();
    public abstract Product GetResult();
  }

  // "ConcreteBuilder1" 
  class ConcreteBuilder1 : Builder
  {
    private Product product = new Product();

    public override void BuildPartA()
    {
      product.Add("PartA");
    }

    public override void BuildPartB()
    {
      product.Add("PartB");
    }

    public override Product GetResult()
    {
      return product;
    }
  }

  // "ConcreteBuilder2" 
  class ConcreteBuilder2 : Builder
  {
    private Product product = new Product();

    public override void BuildPartA()
    {
      product.Add("PartX");
    }

    public override void BuildPartB()
    {
      product.Add("PartY");
    }

    public override Product GetResult()
    {
      return product;
    }
  }

  // "Product" 
  class Product
  {
    ArrayList parts = new ArrayList();

    public void Add(string part)
    {
      parts.Add(part);
    }

    public void Show()
    {
      Console.WriteLine("\nProduct Parts -------");
      foreach (string part in parts)
        Console.WriteLine(part);
    }
  }
 Product Parts -------
PartA PartB Product Parts ------- PartX PartY





Thursday, September 19, 2013

Abstract factory

Abstract factory

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.



Abstract Factory Design Pattern goal is to assemble classes or products that you need for the software.



The abstract factory design pattern is merely an extension of the factory method pattern, which allows you to create objects without being concerned about the actual class of the objects being produced. The abstract factory pattern extends the factory method pattern by allowing more types of objects to be produced.





Let's start with an example first, then we will see how it eventually leads us to the abstract factory pattern.


Starting from the factory method example where we had online bookstores that can choose different book distributors to ship the books to the customers:





In the example, both BookStoreA and BookStoreB choose which distributor (EastCoastDistributor or MidWestDistributor or WestCoastDistributor) to use based on the location of the customer. This logic is in each bookstore's GetDistributor method.

We can extend this factory method pattern to the abstract factory pattern by:

Adding another product that the factories can produce. In this example, we will add Advertisers that help the bookstores advertise their stores online.
Each bookstore can then choose their own distributors and advertisers inside their own GetDistributor and GetAdvertiser method.
After this extension, we now have:





Both bookstores (the factories) have their own GetAdvertiser method that chooses which advertiser to produce, as well as their own GetDistributor method that chooses which distributor to produce.

This allows you to have client code (calling code) such as:


public void Advertise(IBookStore s)    
{       
    IAdverister a = s.GetAdvertiser();
    a.Advertise();    
}



Notice that regardless if you pass in BookStoreA or BookStoreB into the method above, this client code does not need to be changed since it will get the correct advertiser automatically using the internal logics within the factories. It is the factories (BookStoreA and BookStoreB) that determines which advertiser to produce. The same goes for choosing which book distributor to produce.

Below is the UML of the Abstract Factory design pattern, which is what we have in our example: 




The benefit of the Abstract Factory pattern is that it allows you to create a groups of products (the distributors and the advertisers) without having to know the actual class of the product being produced. The result is that you can have client code that does not need to be changed when the internal logic of the factories on which product to produce changed.


Below are the implementation code and the output of the Abstract Factory pattern using our example. Notice that you can change the types of the products (the distributors and the advertisers) being produced by changing the code in the factories (the bookstores) without changing the client code:



public enum CustomerLocation { EastCoast, WestCoast }

class Program
{
    static void Main(string[] args)
    {
        IBookStore storeA = new BookStoreA(CustomerLocation.EastCoast);

        Console.WriteLine("Book Store A with a customer from East Coast:");
        ShipBook(storeA);
        Advertise(storeA);

        IBookStore storeB = new BookStoreB(CustomerLocation.WestCoast);
        Console.WriteLine("Book Store B with a customer from West Coast:");
        ShipBook(storeB);
        Advertise(storeB);
    }

    //**** client code that does not need to be changed  ***
    private static void ShipBook(IBookStore s)
    {
        IDistributor d = s.GetDistributor();
        d.ShipBook();
    }

    //**** client code that does not need to be changed  ***
    private static void Advertise(IBookStore s)
    {
        IAdvertiser a = s.GetAdvertiser();
        a.Advertise();
    }
}

//the factory
public interface IBookStore
{
    IDistributor GetDistributor();
    IAdvertiser GetAdvertiser();
}

//concrete factory
public class BookStoreA : IBookStore
{
    private CustomerLocation location;

    public BookStoreA(CustomerLocation location)
    {
        this.location = location;
    }

    IDistributor IBookStore.GetDistributor()
    {
        //internal logic on which distributor to return
        //*** logic can be changed without changing the client code  ****
        switch (location)
        {
            case CustomerLocation.EastCoast:
                return new EastCoastDistributor();
            case CustomerLocation.WestCoast:
                return new WestCoastDistributor();
        }
        return null;
    }

    IAdvertiser IBookStore.GetAdvertiser()
    {
        //internal logic on which distributor to return
        //*** logic can be changed without changing the client code  ****
        switch (location)
        {
            case CustomerLocation.EastCoast:
                return new RedAdvertiser();
            case CustomerLocation.WestCoast:
                return new BlueAdvertiser();
        }
        return null;
    }
}

//concrete factory
public class BookStoreB : IBookStore
{
    private CustomerLocation location;

    public BookStoreB(CustomerLocation location)
    {
        this.location = location;
    }

    IDistributor IBookStore.GetDistributor()
    {
        //internal logic on which distributor to return
        //*** logic can be changed without changing the client code  ****
        switch (location)
        {
            case CustomerLocation.EastCoast:
                return new EastCoastDistributor();
            case CustomerLocation.WestCoast:
                return new WestCoastDistributor();
        }
        return null;
    }

    IAdvertiser IBookStore.GetAdvertiser()
    {
        //internal logic on which distributor to return
        //*** logic can be changed without changing the client code  ****
        switch (location)
        {
            case CustomerLocation.EastCoast:
                return new BlueAdvertiser();
            case CustomerLocation.WestCoast:
                return new RedAdvertiser();
        }
        return null;
    }
}

//the product
public interface IDistributor
{
    void ShipBook();
}

//concrete product
public class EastCoastDistributor : IDistributor
{
    void IDistributor.ShipBook()
    {
        Console.WriteLine("Book shipped by East Coast Distributor");
    }
}

//concrete product
public class WestCoastDistributor : IDistributor
{
    void IDistributor.ShipBook()
    {
        Console.WriteLine("Book shipped by West Coast Distributor");
    }
}

//the product
public interface IAdvertiser
{
    void Advertise();
}

//concrete product
public class RedAdvertiser : IAdvertiser
{
    void IAdvertiser.Advertise()
    {
        Console.WriteLine("Advertised by RedAdvertiser");
    }
}

//concrete product
public class BlueAdvertiser : IAdvertiser
{
    void IAdvertiser.Advertise()
    {
        Console.WriteLine("Advertised by BlueAdvertiser");
    }
}




SOURCE:



SingleTon

Singleton:
Ensure a class has only one instance, and provide a global point of access to it.


    public class Singleton
    {
        private static Singleton uniqueInstance;
        //other useful instance variables here

        private Singleton()
        {

        }

        public static Singleton getInstance()
        {
            if (uniqueInstance == null)
            {
                uniqueInstance = new Singleton();
            }
            return uniqueInstance;
        }
        //other useful methods here
    }



Where it can be used?
Printer 
For logging
Holding Registry entry in single object.

Wednesday, September 18, 2013

Factory Method Pattern

Factory Method Pattern


Define an interface for creating an object but let sub-classes decide which
instance to instantiate. Factory Method lets a class defer instantiation to
subclasses.




UML class diagram





For better understanding follow the combined post on Abstract Factory and  Factory Method  http://devsid.blogspot.in/2013/09/abstract-factory.html


 participants

    The classes and/or objects participating in this pattern are:
  • Product  (Page)
    • defines the interface of objects the factory method creates
  • ConcreteProduct  (SkillsPage, EducationPage, ExperiencePage)
    • implements the Product interface
  • Creator  (Document)
    • declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.
    • may call the factory method to create a Product object.
  • ConcreteCreator  (Report, Resume)
    • overrides the factory method to return an instance of a ConcreteProduct.

sample code in C#

This structural code demonstrates the Factory method offering great flexibility in creating different objects. The Abstract class may provide a default object, but each subclass can instantiate an extended version of the object.

// Factory Method pattern -- Structural example

using System;

namespace DoFactory.GangOfFour.Factory.Structural
{
  /// <summary>
  /// MainApp startup class for Structural
  /// Factory Method Design Pattern.
  /// </summary>
  class MainApp
  {
    /// <summary>
    /// Entry point into console application.
    /// </summary>
    static void Main()
    {
      // An array of creators
      Creator[] creators = new Creator[2];

      creators[0] = new ConcreteCreatorA();
      creators[1] = new ConcreteCreatorB();

      // Iterate over creators and create products
      foreach (Creator creator in creators)
      {
        Product product = creator.FactoryMethod();
        Console.WriteLine("Created {0}",
          product.GetType().Name);
      }

      // Wait for user
      Console.ReadKey();
    }
  }

  /// <summary>
  /// The 'Product' abstract class
  /// </summary>
  abstract class Product
  {
  }

  /// <summary>
  /// A 'ConcreteProduct' class
  /// </summary>
  class ConcreteProductA : Product
  {
  }

  /// <summary>
  /// A 'ConcreteProduct' class
  /// </summary>
  class ConcreteProductB : Product
  {
  }

  /// <summary>
  /// The 'Creator' abstract class
  /// </summary>
  abstract class Creator
  {
    public abstract Product FactoryMethod();
  }

  /// <summary>
  /// A 'ConcreteCreator' class
  /// </summary>
  class ConcreteCreatorA : Creator
  {
    public override Product FactoryMethod()
    {
      return new ConcreteProductA();
    }
  }

  /// <summary>
  /// A 'ConcreteCreator' class
  /// </summary>
  class ConcreteCreatorB : Creator
  {
    public override Product FactoryMethod()
    {
      return new ConcreteProductB();
    }
  }
}

Output
Created ConcreteProductA
Created ConcreteProductB

This real-world code demonstrates the Factory method offering flexibility in creating different documents. The derived Document classes Report and Resume instantiate extended versions of the Document class. Here, the Factory Method is called in the constructor of the Document base class.

// Factory Method pattern -- Real World example

using System;
using System.Collections.Generic;

namespace DoFactory.GangOfFour.Factory.RealWorld
{
  /// <summary>
  /// MainApp startup class for Real-World
  /// Factory Method Design Pattern.
  /// </summary>
  class MainApp
  {
    /// <summary>
    /// Entry point into console application.
    /// </summary>
    static void Main()
    {
      // Note: constructors call Factory Method
      Document[] documents = new Document[2];

      documents[0] = new Resume();
      documents[1] = new Report();

      // Display document pages
      foreach (Document document in documents)
      {
        Console.WriteLine("\n" + document.GetType().Name + "--");
        foreach (Page page in document.Pages)
        {
          Console.WriteLine(" " + page.GetType().Name);
        }
      }

      // Wait for user
      Console.ReadKey();
    }
  }

  /// <summary>
  /// The 'Product' abstract class
  /// </summary>
  abstract class Page
  {
  }

  /// <summary>
  /// A 'ConcreteProduct' class
  /// </summary>
  class SkillsPage : Page
  {
  }

  /// <summary>
  /// A 'ConcreteProduct' class
  /// </summary>
  class EducationPage : Page
  {
  }

  /// <summary>
  /// A 'ConcreteProduct' class
  /// </summary>
  class ExperiencePage : Page
  {
  }

  /// <summary>
  /// A 'ConcreteProduct' class
  /// </summary>
  class IntroductionPage : Page
  {
  }

  /// <summary>
  /// A 'ConcreteProduct' class
  /// </summary>
  class ResultsPage : Page
  {
  }

  /// <summary>
  /// A 'ConcreteProduct' class
  /// </summary>
  class ConclusionPage : Page
  {
  }

  /// <summary>
  /// A 'ConcreteProduct' class
  /// </summary>
  class SummaryPage : Page
  {
  }

  /// <summary>
  /// A 'ConcreteProduct' class
  /// </summary>
  class BibliographyPage : Page
  {
  }

  /// <summary>
  /// The 'Creator' abstract class
  /// </summary>
  abstract class Document
  {
    private List<Page> _pages = new List<Page>();

    // Constructor calls abstract Factory method
    public Document()
    {
      this.CreatePages();
    }

    public List<Page> Pages
    {
      get { return _pages; }
    }

    // Factory Method
    public abstract void CreatePages();
  }

  /// <summary>
  /// A 'ConcreteCreator' class
  /// </summary>
  class Resume : Document
  {
    // Factory Method implementation
    public override void CreatePages()
    {
      Pages.Add(new SkillsPage());
      Pages.Add(new EducationPage());
      Pages.Add(new ExperiencePage());
    }
  }

  /// <summary>
  /// A 'ConcreteCreator' class
  /// </summary>
  class Report : Document
  {
    // Factory Method implementation
    public override void CreatePages()
    {
      Pages.Add(new IntroductionPage());
      Pages.Add(new ResultsPage());
      Pages.Add(new ConclusionPage());
      Pages.Add(new SummaryPage());
      Pages.Add(new BibliographyPage());
    }
  }
}

Output
Resume -------
 SkillsPage
 EducationPage
 ExperiencePage

Report -------
 IntroductionPage
 ResultsPage
 ConclusionPage
 SummaryPage
 BibliographyPage







Code Formater

Paste Here Your Source Code
Source Code Formatting Options
1) Convert Tab into Space :
2) Need Line Code Numbering :
3) Remove blank lines :
4) Embeded styles / Stylesheet :
5) Code Block Width :
6) Code Block Height :
7) Alternative Background :
Copy Formatted Source Code
 
Preview Of Formatted Code