Factory Method Design Pattern – Sequence Diagrams

As defined by the GOF, the Factory Method Design Pattern is used to “Define an interface for creating an object, but let the classes which implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses”. Factory methods can be used in place of constructors to create objects, doing so in a more elegant and controllable way (Joshua Bloch said in an interview that only classes that were designed for subclassing should have constructors).

In its most simplest form, a factory method simply replaces the constructor:

And we can show how this works using a sequence diagram:

We can obviously add more functionality to the createProduct() method, but this is trivial. A more complex example is to use polymorphism to get factories that can create different kinds of objects, all of which comply to the same abstraction. This is how it is described by the GOF (fairly overlapping the abstract factory pattern):

This implementation completely decouples the client from the implementation. The client is only aware of a Creator and an Abstraction with complete disregard of their implementations. The creator is somehow available to the client (via dependency injection). So now that we have a static model, is there a way to describe the dynamics of this diagram using a sequence diagram? Let’s try:

It turns out that to model the flow of operations I am actually modeling how polymorphism, late binding and all that stuff works. I guess that in this case, a sequence diagram is not only irrelevant, but actually confusing. But I had to try 🙂

Enhanced by Zemanta

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.