Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to build a factory

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?

like image 713
guyl Avatar asked Aug 31 '11 11:08

guyl


1 Answers

In the first version the interface of ShapeFactoryImplementation remains the same. In the second every time you add a new method you have a new interface.

like image 199
Matteo Avatar answered Sep 28 '22 09:09

Matteo