It is not required to use an abstract class
for a factory. It mainly depends on the complexity of the objects you want to create and how much code you can re-use among factories.
The example you link to is somewhat contrived to demonstrate the use of the abstract factory pattern. The example creates an abstract factory (the 'interface' of the factory) which is then extended with a ShapeFactory
and a ColorFactory
. The concrete ShapeFactory
returns null when getColor()
is called and vice versa. This is a violation of the single responsibility principle.
Instead I would suggest this design to show that you don't always need an abstract factory, but can use a simpler factory method pattern as well.
public interface Shape {
void Draw();
}
public class Square : Shape {
public void Draw() { //... }
}
public class Circle : Shape {
public void Draw() { //... }
}
public enum ShapeType {
Square,
Circle
}
public class ShapeFactory {
public Shape CreateShape(ShapeType type) {
switch (type) {
case ShapeType.Square:
return new Square();
case ShapeType.Circle:
return new Circle();
default:
throw new Exception("Unsupported ShapeType: " + type);
}
}
}
Use the concrete ShapeFactory like this:
var factory = new ShapeFactory();
var circle = factory.CreateShape(ShapeType.Circle);
Edit: Just to nitpick... In an abstract factory pattern, the base factory would always be abstract. This is because the base class (or interface) it would create isn't usable in itself. In reality you could work with a Circle
or Square
, but not with a Shape
. That doesn't mean that your code can't deal with shapes in general.