Search code examples
javadesign-patternsgraphfactory-pattern

Is this right usage Of factory method


As i understood Factory design pattern is used to create object instead of constructors

in a previous question i explained my situation which is :
I have a complex Network represented as hypergraph Hypergraph vertices are from various type :image,tag ....
I should create thousand of vertices it will be hard to create it manually! so i thought that factory pattern may help me in this case

I drew two possible diagram using yUML but i can't decide what is the most appropriate to my situation

first diagram

second diagram


Solution

  • Actually, both depict the Factory Method pattern.

    But, as we are speaking of mutiple factories, the first image is a better, less coupled, more extensible, easier to maintain approach.

    Just, in the first image, as you have a yet small diagram, it is better to put a dashed line from AbstractVertexFactory to Vertex, as there is a dependency relationship between these classes.

    Also, the second image is missing all the dashed dependency lines. This does not make this diagram incorrect, and it still does depict the factory method pattern, the only drawback is that it is more confusing without the mentioned lines.

    Explanation of why the first is better than the second:

    • Less coupled: In the first case, if you change/delete the TagVertex, no clients of the ImageFactory (and potetially other factories) are affected.
    • More extensible and easier to maintain: Same principle. If you change a product (Vertex in your scenario) class, no client of other factory is affected. Also you can add factories freely without need to change existing code.