preface

There are many summaries of this model, but most of them are quite official, and many copy and paste are difficult to understand, so I will summarize them again in my own words.

The body of the

Simple Factory model

The simple factory pattern is not a design pattern and is not discussed here.

Factory method pattern

A creative design pattern

Here’s a straightforward example:

  1. Now our company has started a transportation business to transport goods from one city in China to another city by car.

Note: the business here involves shipping, not doing anything else.

  1. As our business has grown, many companies have contacted us asking us to start the overseas shipping business, that is, to ship goods to overseas cities.

Note: the business function here is still transportation, but using other tools ship.

The class diagram

explain

The factory method pattern does not care what tools are used, leaving it to subclasses to implement (all factory patterns are left to subclasses to implement), just how the transport operation is performed.

conclusion

Usually based on a factory method, focusing on doing one thing for one product is called the factory method model.

Abstract Factory pattern

A creative design pattern

Here’s a straightforward example:

Following the example above:

  1. Since there are many notebooks in stock in our company, the leader wants to sell notebooks on the basis of transportation, so he needs to sell notebooks while transporting.

Note: There's more business here, and you need to do two things at once.

The class diagram

explain

A factory is responsible for multiple product categories

conclusion

Abstract factory pattern, in which a factory is responsible for multiple product categories, usually has multiple factory methods, is an upgrade of the factory method pattern.

conclusion

  1. Abstract factories and factory method patterns are not limited to whether their root parent uses an interface or an abstract class.
  2. The factory method pattern targets a factory method with a clear and single factory responsibility.
  3. The abstract factory pattern addresses multiple factory methods, with factories responsible for multiple product categories.
  4. You don’t need an abstract factory if you don’t have a product family in your program.