Factory


Abstract Factory

Subclasses decide which concrete class to create
Hides the creation and implementation
Use two abstract classes Factory and Product. Instances are then inherited from these abstract classes


Problem

The following code is on the client

If (choice == "Car") 
{
// call car class and it's methods
Car c = new car();
c.buy();
}
If (choice == "bike")
{
// call bike class and it's methods
Bike b = new Bike();
b.buy()
}

1) In case in future if there is any other vehicle added then we need to change the client functionality.

2) The above client code depicts that there are classes Car, Bike, and a method Buy. There is no security at the client side.

3) Need to use the new keyword in client classes.


Solution


IChoice objInvoice; 
objInvoice = FactoryClass.FactoryChoice.getChoiceObj(txtChoice.Text.Trim());


Using a new Factory class fixes problem 3

public class FactoryChoice 
{
    static public IChoice getChoiceObj(string cChoice)
     {
        IChoice objChoice=null;
        if (cChoice.ToLower() == "car")
        {
            objChoice = new clsCar();
        }
        else if (cChoice.ToLower() == "bike")
        {
            objChoice = new clsBike();
        }
        else
        {
            objChoice = new InvalidChoice();
        }
        return objChoice;
    }
}


Using an interface fixes problem 1 and 2

public interface IChoice 
{
    string Buy();
}

public class clsBike:IChoice
{
    public string Buy()
    {
        return ("You choose Bike");
    }
}
 
public class clsCar:IChoice
{
    public string Buy()
    {
        return ("You choose Car");
    }
}



Factory Method




© 2017 Better Solutions Limited. All Rights Reserved. © 2017 Better Solutions Limited

Top

PrevNext