Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Thursday, July 10, 2014

What is the difference between static class and singleton pattern?

In the first overview; we see both singleton class and static class are look similar. But there are many difference and here are the major points.

The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common IME), so you can pass around the singleton as if it were "just another" implementation.

A singleton allows access to a single created instance - that instance (or rather, a reference to that instance) can be passed as a parameter to other methods, and treated as a normal object.

A static class allows only static methods.

Singleton object stores in Heap but, static object stores in stack.

We can clone the object of Singleton but, we can not clone the static class object.

Singleton class follow the OOP(object oriented principles) but not static class
we can implement interface with Singleton class but not with Static class.

Friday, July 4, 2014

Command Design Pattern

 

Implementing the Command interface

First things first: all command objects implement the same interface, which consists of one method.

here's the Command interface:

 public interface Command{  
   public void execute();  
 }  

Implementing a Command to turn a light on

Now, let's say you want to implement a command for turning a light on.
Referring to our set of vendor classes, the Light class has two methods: on() and off(). Here's how you can implement this as a command:


public class LightOnCommand : Command{  
   Light light;  
   public LightOnCommand(Light light){  
     this.light=light;  
   }  
   public void execute(){  
     light.on();  
   }  
 }  

Using the command object

Okey, let's make things simple: say we've got a remote control with only one button and corresponding slot to hold a device to control:


public class SimpleRemoteControl{  
   //we have one slot to hold our command which will control one device.  
   Command slot;  
   public SimpleRemoteControl(){}  
   //we have a method for setting the command the slot is going to control.   
   //This could be called multiple times if the client of this code wanted   
   //to change the behavior of the remote button.  
   public void setCommand(Command command){  
     slot=command;  
   }  
   //This method is called when the button is pressed .   
   //All we do take the current command bound to the slot and  
   //call its execute() method.  
   public void buttonWasPressed(){  
     slot.execute();  
   }  
 }

Creating a simple test to use the Remote Control

Here's just a bit of code to test out the simple remote control. Let's take a look and we'll point out how the pieces match the Command Pattern diagram:


//This is our client in Command pattern-speak.  
 public class RemoteControlTest{  
   public static void main(String[] args){  
     //The remote is our invoker; it will be passed a command object that can be used to make  
     //requests.  
     SimpleRemoteControl remote = new SimpleRemoteControl();  
     //Now we create a Light object, this will be the Receiver of the request.  
     Light light= new Light();  
     //Here, creates a Command and pass it to the Receiver.  
     LightOnCommand lightOn=new LightOnCommand(light);  
     remote.setCommand(lightOn);//Here, pass the command to the invoker.  
     remote.buttonWasPressed();//And then we simulate the button being pressed.  
   }  
 }  

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:



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