Articles → .NET DESIGN PATTERN → Factory Method Design Pattern
Factory Method Design Pattern
Click to Enlarge
- Create the interfaces of product.
- Create concrete product classes which will inherit the product interface. In the above analogy if the user asks for simple bread and a garlic bread then 2 classes SimpleBread and GarlicBread will be created which will be inherited from IBread interface.
- Create a class for factory that contains the method that will return the product interface.
- Finally use the factory class to get the product.
Step I - Create The Interfaces Of Product.
// A Simple Interface
public interface iCalc {
int ReturnResult(int arg1, int arg2);
}
Step II - Create Concrete Product Classes Which Will Inherit The Product Interface.
public class Sum: iCalc {
public int ReturnResult(int arg1, int arg2) {
return (arg1 + arg2);
}
}
public class Difference: iCalc {
public int ReturnResult(int arg1, int arg2) {
return (arg1 - arg2);
}
}
public class Multiplication: iCalc {
public int ReturnResult(int arg1, int arg2) {
return (arg1 * arg2);
}
}
public class Division: iCalc {
public int ReturnResult(int arg1, int arg2) {
return Convert.ToInt32(arg1 / arg2);
}
}
Step III - Create A Class For Factory That Contains The Method That Will Return The Product Interface
public enum CalculationType {
Sum,
Difference,
Multiplication,
Division
}
public class Calculator {
public static iCalc CreateOperation(CalculationType oCalculationType) {
if (oCalculationType == CalculationType.Sum) {
return new Sum();
}
else if (oCalculationType == CalculationType.Difference) {
return new Difference();
}
else if (oCalculationType == CalculationType.Multiplication) {
return new Multiplication();
}
else if (oCalculationType == CalculationType.Division) {
return new Division();
}
else {
throw new ApplicationException("Problem Occurs");
}
}
}
Step IV - Finally Use The Factory Class To Get The Product
iCalc x = Calculator. CreateOperation(CalculationType.Sum);
int abc = x.ReturnResult(1, 2)