(Abstract Factory) Why do this when you can't use new methods in the derived classes?

42 views Asked by At

I am reading about the Abstract Factory Pattern. As far as I understand, the client code is going to have references to the constructed objects via the abstract interface. This means that if you extend the abstract factory to make objects that have new methods, you can't call them. This seems like a tight restriction. Why have all these subclasses when the client won't even be able to access any new methods or variables?

1

There are 1 answers

0
eugenioy On BEST ANSWER

The fact that the user of the Abstract Factory can't use the constructor of the classes and is forced to access them through the abstract interface is precisely one of the points of using that pattern.

Suppose you are implementing a class that will send emails to customers.

You can send the customer QuoteEmails and FollowUpEmails.

You have two options:

  • Use new FollowUpEmail() and new QuoteEmail() each time you want to send one of those
  • Make your code work with an EmailFactory and call factory.createFollowUpEmail() and factory.createQuoteEmail() when you need to create them

Now, if using the first choice, it'd be really hard to introduce different styles for FollowUpEmail and QuoteEmail.

Perhaps you want to send Christmas themed in December, or send formal emails in some particular situations.

So you could create ChristmasQuoteEmail and FormalQuoteEmail, but you'd need to modify all the code that creates emails to use them.

With the second option (abstract factory), your code does not know how the emails are created. So just by sending a ChristmasEmailFactory to your code, when your code uses factory.createQuoteEmail(), the right email will be created.