Design Patterns – Can a Class Be a Factory for One Concrete Type?

design-patternsfactoryfactory-methodfactory-patternnaming

I have a simple class called Link that contains some properties, and use different classes for creating different types of links.

My code looks like this:

class Link {
  String reference, label, target, ...
}
interface LinkFactory {
  Link createLink(Person person)
}
class EditLinkFactory implements LinkFactory {
  Link createLink(Person person) {
    // complex "create edit link" logic goes here
  }
}
class DeleteLinkFactory implements LinkFactory {
  Link createLink(Person person) {
    // complex "create delete link" logic goes here
  }
}

I have appended the postfix Factory to the classes creating Links. However, according to Wikipedia, the factory method pattern is used in the following case:

In class-based programming, the factory method pattern is a creational
pattern that uses factory methods to deal with the problem of creating
objects without having to specify the exact class of the object that
will be created.

In my case there is only one exact class of objects that will be created by each of the factory classes. There is never another one.

I therefore wonder: do my Factory classes correspond to the factory pattern ? Or would this naming be confusing as they do not adhere to the factory pattern according to the textbooks?

Best Answer

In short

Yes, a factory class may create only one kind of objects. It is fully ok to use a Factory prefix or suffix in the name of such classes.

Some more arguments

According to GoF (still the reference textbook about design patterns), the factory method pattern:

defines an interface for creating an object, but let subclasses decide which class to instantiate.

In the structural description of the pattern, GoF use Creator for naming the interfaces or classes that define a factory method. But their examples use several naming conventions, their recommendation in that matter being:

It's good practice to use a naming convention that makes clear you're using factory methods

Your choice is completely in line with that recommendation and perfectly ok.

Moreover, the fact that your concrete factory implementations create only one kind of Link is not an issue either. GoF explain that a parameterized factory method is a factory that is able to create different kind of objects depending on some parameters. But this is only one of the many implementation possibilities described and not a requirement for a factory.

Note: another pattern, the abstract factory aims to use the principle of the factory for creating objects belonging to a family of related classes. This is one particular kind of factory, and althought it's commonly used, it doesn't hold a monopoly on the Factory pre-/sufix