Monday, April 7, 2014

Factory Design Pattern

http://www.codeproject.com/Articles/184765/Factory-Method-Design-Pattern
You can see this and other great articles on Design Patterns here.
The Factory Method Design Pattern allows you to create objects without being bothered on what is the actual class being created. The benefit is that the client code (calling code) can just say "give me an object that can do XYZ" without knowing what is the actual class that can do "XYZ".
Let's do an example to see how it works. Let’s say you are an online bookstore and people come to your website to buy books. When a customer orders a book, you just have another book distributor send the book directly to the customer. You are a middle man and you don’t stock the books. You have many distributors that you can choose to send the books directly to your customers.
Since you have many distributors, you have the following logic to determine which distributor to choose for sending the books to your customers:
  • If the customer is in the east coast, you will use EastCoastDistributor
  • If the customer is in the mid-west, you will use MidWestDistributor
  • If the customer is in the west coast, you will use WestCoastDistributor
The key is your customer should not care which distributor you choose because they will get their books regardless. It is completely hidden from the customer's point of view, and they should not be concerned about it. You, the online bookstore, are the one that determines the distributor to use.
Using this example, we can have the following UML:
The logic that decides which distributor to use is in the BookStore.GetDistributor method. The method returns IDistributor with the following logic:
  • If the customer is in the east coast, return EastCoastDistributor
  • If the customer is in the mid-west, return MidWestDistributor
  • If the customer is in the west coast, return WestCoastDistributor
This method is the factory method that returns a product (a distributor). Each of the distributor implements the IDistributor interface, which has the ShipBook method. The client code just says "give me a distributor that can ShipBook" without having to know which distributor you are going to return.
You can now have client code (calling code) such as:
IDistributor b = bookStore.GetDistributor();
//the client gets the distributor without having
//to know which distributor is being used
Notice that this client code don’t need to care which distributor is being created, and this is key to the Factory Method pattern.
Taking another step further, we can abstract out the BookStore as an interface and have more types of bookstores, as shown below:
Now you can have client code such as the following that does not need to be changed if the logic for choosing the distributor changes:
//this client code will not need to be changed even
//if the logic for the distributor changed
public void ShipBook(IBookStore s)    
{        
    IDistributor d = s.GetDistributor();
    d.ShipBook();
}
You can pass in any bookstore that implements the IBookStore interface to this method and it will use the correct distributor automatically. The benefit is that this client code does not need to be changed when you change the logic of the GetDistributor method of the bookstores.
Below is the UML of the Factory Method Design Pattern, which is what we have in our example:

Below are the implementation code and the output of the Factory Method pattern using our example. Notice that you can change the code in the factory without changing the client code for the factory to produce different products (distributors):
public enum CustomerLocation { EastCoast, MidWest, WestCoast }
class Program
{     
    static void Main(string[] args)
    {
        Console.WriteLine("East Coast Customer:");
        IBookStore bookstore = new BookStoreA(CustomerLocation.EastCoast);
        ShipBook(bookstore);

        Console.WriteLine("Mid West Customer:");
        bookstore = new BookStoreA(CustomerLocation.MidWest);
        ShipBook(bookstore);

        Console.WriteLine("West Coast Customer:");
        bookstore = new BookStoreA(CustomerLocation.WestCoast);
        ShipBook(bookstore);
    }

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

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

//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.MidWest:
                return new MidWestDistributor();
            case CustomerLocation.WestCoast:
                return new WestCoastDistributor();
        }
        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 MidWestDistributor : IDistributor
{
    void IDistributor.ShipBook()
    {
        Console.WriteLine("Book shipped by Mid West Distributor");
    }
}

//conceret product
public class WestCoastDistributor : IDistributor
{
    void IDistributor.ShipBook()
    {
        Console.WriteLine("Book shipped by West Coast Distributor");
    }
}
Liked this article? You can see this and other great articles on Design Patterns here.
************************************************************************************************************
http://sourcemaking.com/design_patterns/factrory_method/c-sharp-dot-net
Defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
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.
using System; using System.Collections;   class MainApp   {     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.Read();     }   }   // "Product"   abstract class Product   {   }   // "ConcreteProductA"   class ConcreteProductA : Product   {   }   // "ConcreteProductB"   class ConcreteProductB : Product   {   }   // "Creator"   abstract class Creator   {     public abstract Product FactoryMethod();   }   // "ConcreteCreator"   class ConcreteCreatorA : Creator   {     public override Product FactoryMethod()     {       return new ConcreteProductA();     }   }   // "ConcreteCreator"   class ConcreteCreatorB : Creator   {     public override Product FactoryMethod()     {       return new ConcreteProductB();     }   }

*********************************************************************************

http://www.c-sharpcorner.com/UploadFile/kalisk/factory-method-design-pattern-using-C-Sharp/


Factory Method Design Pattern using C#

Concerns:
  • Which object needs to be created.
  • Managing the life time of the object.
  • Managing the build-up and tear down concerns of the object.
Definition:

"Define an interface for creating an object, but let subclasses decide which class to instantiate"

C# Implementation of Factory method

abstract class Factory 
    { 
        public abstract Product GetProduct(); //Factory Method Declaration 
    
}

class
 concreteFactoryforProcuct1 : Factory 
    { 
        public override Product GetProduct() //Factory Method Implementation 
            
                return new Product1(); 
            } 
    }
class concreteFactoryforProcuct2 : Factory 
    {
        public override Product GetProduct() //Factory Method Implementation 
            
                return new Product2(); 
            } 
    }

interface
 Product 
    { 
        void GetDetails(); 
    }

class
 Product1 : Product 
    { 
        public void GetDetails() 
        { 
            Console.WriteLine("Product1 Details are Called"); 
        } 
    } 

class
 Product2 : Product 
    { 
        public void GetDetails() 
        { 
            Console.WriteLine("Product2 Details are called"); 
        } 
    }
protected void Page_Load(object sender, EventArgs e) 
{

    Factory[] objFactories = new Factory[2]; 
    objFactories[0] = new concreteFactoryforProcuct1(); 
    objFactories[1] = new concreteFactoryforProcuct2(); 
    foreach (Factory objFactory in objFactories) 
   
 { 
        Product objProduct = objFactory.GetProduct(); 
        objProduct.GetDetails(); 
    } 
}
**************************
http://www.codeproject.com/Articles/185349/Abstract-Factory-Design-Pattern
**********************************************************
http://www.codeproject.com/Tips/741810/Abstract-Factory-Design-Pattern-in-Csharp
*********************
http://www.codeproject.com/Articles/492900/From-No-Factory-to-Factory-Method
http://www.codeproject.com/Articles/716413/Factory-Method-Pattern-vs-Abstract-Factory-Pattern
http://www.codeproject.com/Articles/328409/Understanding-and-Implementing-Factory-Pattern-in
*****************************************
http://www.codeproject.com/Tips/102169/Design-patterns-Part-I-Factory
http://www.codeproject.com/Articles/57421/Design-Patterns-Part-The-Factory-Pattern
*******************************
http://www.codeproject.com/Articles/738043/Design-Patterns-in-ASP-NET
***********************************************
http://www.codeproject.com/Articles/68670/The-Factory-Pattern
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
static class Module1
{


    public static void Main()
    {
        SuperShopFranchisee franchisee = new SuperShopFranchisee();
        franchisee.OrderBat("hardball");

        //just to hold the screen
        Console.ReadLine();

    }

    //A framework for our franchisees
    public abstract class BatFactory
    {

        public Bat OrderBat(string choice)
        {

            Bat myBat = this.CreateBat(choice);

            myBat.clean();
            myBat.applyGrip();
            myBat.applyLogo();
            myBat.applyCover();
            myBat.pack();

            return myBat;

        }

        public abstract Bat CreateBat(string choice);

    }

    //one of our franchisee implemented our framework
    public class SuperShopFranchisee : BatFactory
    {

        public override Bat CreateBat(string choice)
        {

            Bat myBat = null;

            switch (choice)
            {

                case "hardball":
                    myBat = new AddidassHardBallBat();

                    break;
                case "softball":
                    myBat = new AddidassSoftBallBat();

                    break;
                case "plasticball":
                    myBat = new AddidassPlasticBallBat();

                    break;
            }

            return myBat;

        }

    }

    public class Bat
    {

        public Bat()
        {
            //default constructor
        }

        public void clean()
        {
            Console.WriteLine("Bat has been Cleaned !");
        }

        public void applyGrip()
        {
            Console.WriteLine("Grip has been Applied !");
        }

        public void applyLogo()
        {
            Console.WriteLine("Logo has been Applied !");
        }

        public void applyCover()
        {
            Console.WriteLine("Cover has been Applied !");
        }

        public void pack()
        {
            Console.WriteLine("Packing Done !");
        }

    }

    public class AddidassHardBallBat : Bat
    {

        public AddidassHardBallBat()
        {
            Console.WriteLine("This is addidas hard ball bat !");
        }

    }


    public class AddidassSoftBallBat : Bat
    {

        public AddidassSoftBallBat()
        {
            Console.WriteLine("This is addidas Soft ball bat !");
        }

    }

    public class AddidassPlasticBallBat : Bat
    {

        public AddidassPlasticBallBat()
        {
            Console.WriteLine("This is addidas Plastic ball bat !");
        }

    }


}
***********************


No comments:

Post a Comment