Factory Design Pattern

Factory Design Pattern

This is nothing new, it has been published in one of the 23 "Gang of Four" Object Oriented design patterns. I am just putting together simple generic program that make sense and is easy to digest, to describe how Factory design pattern works, in semi-Layman term.

The idea is to decide which class to instantiate based on a condition that we have, provided that the classes to choose from contain methods of the same signatures and follow a common Interface. (Following a common Interface helps ensuring that the methods defined in the Interface are built with identical signatures).

So I am setting up an Interface IProduct, with implementations of ConcreteProduct1, ConcreteProduct2, and InvalidProduct classes. Next I setup an Abstract Factory (AFactory) class with a concrete Factory class implementation (ConcreteFactory) to house an override method, where the decision logic is coded.

The Main Program can then instantiate the Concrete Factory class, and invoke its Method to decide which class to instantiate. After that we will invoke a method in the corresponding class, whichever class was instantiated by the Factory Method.

The code goes like this:

// Factory Design Pattern - OO Design to decide which class to instantiate based on a condition at hand
// Without using a direct If Statement in the Main Program to promote scalability of future additions of new classes.
// Using Concrete Factory class that implements Abstract Factory Class, it can override stubed out Factory Method
// with real factory Method that decides which class to instantiate using an if-else if or switch statement
namespace ConsoleFactoryDesignPattern
{
public class Program
{
public void Main(string[] args)
{
string choice;
do
{
Console.Write("Enter Product to test (1 OR 2, 'x' for Exit) : ");
choice = Console.ReadLine();
ConcreteFactory cf = new ConcreteFactory();
IProduct p = cf.FactoryMethod(choice);
p.TestProduct();
} while (choice.ToLower() != "x");
}
}

public interface IProduct
{
void TestProduct();
}

public class ConcreteProduct1 : IProduct
{
public void TestProduct()
{
Console.WriteLine("Testing product 1");
}
}

public class ConcreteProduct2 : IProduct
{
public void TestProduct()
{
Console.WriteLine("Testing product 2");
}

}

public class InvalidProduct : IProduct
{
public void TestProduct()
{
Console.WriteLine("Invalid Product");
}

}

public abstract class AFactory
{
public abstract IProduct FactoryMethod(string type);
}

class ConcreteFactory : AFactory
{
public override IProduct FactoryMethod(string type)
{
if (type == "1")
return new ConcreteProduct1();
else if (type == "2")
return new ConcreteProduct2();
else
return new InvalidProduct();
}
}


}

Console screenshot:

 

要查看或添加评论,请登录

社区洞察

其他会员也浏览了