22 March 2015

Factory Method Patterns in C#

Factory Method Patterns

Definition: In Factory pattern, we create object without exposing the creation logic. In this pattern, an interface is used for creating an object, but let subclass decide which class to instantiate. The creation of object is done when it is required. The Factory method allows a class later instantiation to subclasses.

Uses of Factory Method Patterns

1.    creation of object is done when it is required.
2.    The process of objects creation is required to centralize within the application.
3.    A class (creator) will not know what classes it will be required to create.


interface Product
{

}

class ConcreteProductA : Product
{
}
class ConcreteProductB : Product
{
}
abstract class Creator
{
 public abstract Product FactoryMethod(string type);
}
class ConcreteCreator : Creator
{
 public override Product FactoryMethod(string type)
 {
 switch (type)
 {
 case "A": return new ConcreteProductA();
 case "B": return new ConcreteProductB();
 default: throw new ArgumentException("Invalid type", "type");
 }
 }
}

No comments:

Post a Comment

Comments Welcome

Consistency level in Azure cosmos db

 Consistency level in Azure cosmos db Azure Cosmos DB offers five well-defined consistency levels to provide developers with the flexibility...