I have been reading about Factory pattern a lot lately. I am trying to figure out the best way to implement it. In the book C # Agile Principles patterns and practice the recommendation is to create the Factory like this:
public class ShapeFactoryImplementation : ShapeFactory {
public Shape Make(string name) {
if (name.Equals("Circle"))
return new Circle();
else if (name.Equals("Square"))
return new Square();
else
throw new Exception("ShapeFactory cannot create: {0}", name);
}
}
Rather than...
public class ShapeFactoryImplementation : ShapeFactory {
public Shape MakeCircle() {
return new Circle();
}
public Shape MakeSquare() {
return new Square();
}
}
Please tell me what are your thoughts? Or maybe there is a better way to implement the factory pattern?
The main point of the factory pattern is to de-couple the client from the creation of objects.
In your second example, the client has hard-coded the shape to create, such as MakeCircle
, and therefore tightly couples the object creation and the client.