In an abstract factory pattern, the main abstract factory class, should it always be an abstract class?
All example I see in Abstract factory Pattern . They use an abstract class to give an Abstraction for plants.
Should you always use abstract class
?
Given the circumstances, we can happily use the Interface .
If we use an interface , would that violate the design principle?
The example I read
source to share
Not required to be used abstract class
for a factory. It mainly depends on the complexity of the objects you want to create and how much code you can reuse between factories.
The example you link to has come up somewhat to demonstrate the use of the abstract factory pattern. The example creates an abstract factory ("interface" factory), which is then extended with ShapeFactory
and a ColorFactory
. Concrete ShapeFactory
returns null when called getColor()
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 it can use a simpler factory method pattern .
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 a specific ShapeFactory like this:
var factory = new ShapeFactory();
var circle = factory.CreateShape(ShapeType.Circle);
Edit: Just for the nitpick ... In an abstract factory pattern, the base factory will always be abstract. This is because the base class (or interface) that it created is not used by itself. You can actually work with Circle
or Square
, but not with Shape
. This does not mean that your code cannot deal with forms in general.
source to share