Factory Pattern
Summary: When the object construction is complicated, needing multiple arguments, we should create a separate function (Factory Method) or class (Factory), which is responsible for the creation of the entire object.
Problem examples
Suport of multiple databases
Multiple data sources: Serial port, ethernet port, device driver
Diferent report types
Multiple data sources: Serial port, ethernet port, device driver
Diferent report types
Solution
Abstract class
Generalized interface
A Factory creates instances of the concrete classes
Problem: we need to create a Point object, that may be either Cartesian or Polar.Generalized interface
A Factory creates instances of the concrete classes
Sample Code
Factory Method Solution
public class Point
{
private double x, y;
private Point (double x, double y)
{
this.x = x;
this.y = y;
}
public static Point NewCartesianPoint(double x, double y)
{
return new Point(x, y);
}
public static Point NewPolarPoint(double rho, double theta)
{
return new Point(rho*Math.Cos(theta), rho*Math.Sin(theta));
}
public override string ToString()
{
return $"x: {x}, y: {y}";
}
}
Usage
var point = Point.NewCartesianPoint(10,20);
System.Console.WriteLine(point);
Factory Class Solution
public class PointFactory
{
public static Point NewCartesianPoint(double x, double y)
{
return new Point(x, y);
}
public static Point NewPolarPoint(double rho, double theta)
{
return new Point(rho*Math.Cos(theta), rho*Math.Sin(theta));
}
}
public class Point
{
private double x, y;
public Point (double x, double y)
{
this.x = x;
this.y = y;
}
public override string ToString()
{
return $"x: {x}, y: {y}";
}
}
Usage
var point = PointFactory.NewCartesianPoint(10,20);
System.Console.WriteLine(point);
Comments
Post a Comment