Design patterns Factory Factory method


The Factory method pattern is a creational pattern that abstracts away the instantiation logic of an object in order to decouple the client code from it.

When a factory method belongs to a class that is an implementation of another factory pattern such as Abstract factory then it is usually more appropriate to reference the pattern implemented by that class rather than the Factory method pattern.

The Factory method pattern is more commonly referenced when describing a factory method that belongs to a class which is not primarily a factory.

For instance, it may be advantageous to place a factory method on an object that represents a domain concept if that object encapsulates some state that would simplify the creation process of another object. A factory method may also lead to a design that is more aligned with the Ubiquitous Language of a specific context.

Here's a code example:

//Without a factory method
Comment comment = new Comment(authorId, postId, "This is a comment");

//With a factory method
Comment comment = post.comment(authorId, "This is a comment");