2

All the example i see of Abstract factory Pattern They use an abstract class to give the Abstraction for factories.
Is it always required to use abstract class?

Given the circumstances we can happily use Interface.
If we use interface does it going to violate the Design principle?

Example I was Reading

Tutorials Point
oodesign

Carbine
  • 7,849
  • 4
  • 30
  • 54
Saif
  • 6,804
  • 8
  • 40
  • 61
  • using an Interface is as good as using an abstract class – onof Apr 28 '15 at 09:30
  • possible duplicate of [Why does Abstract Factory use abstract class instead of interface?](http://stackoverflow.com/questions/18840227/why-does-abstract-factory-use-abstract-class-instead-of-interface) – Carbine Apr 28 '15 at 09:39

3 Answers3

1

Interfaces and their methods are implicitly abstract so it's totally ok to use interface instead of abstract cass, but in order to mantain the abstract Design you must implement one of both...

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
1

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.

0

1.Factory is an abstract class.
2.Factory can create any subclass of an interface or abstract class.
3.The factory method return type is an interface or abstract class.

Afsun Khammadli
  • 2,048
  • 4
  • 18
  • 28