An example of Java factory pattern

An example of Java factory pattern

The "factory" in the factory method is the same as what we usually understand: it is used to produce products.

The customer is to deal with the product, so the significance of the factory method model is to separate the customer from the product, so as to achieve the purpose of decoupling and more flexibility.

Generally, we have an abstract class of products, and then several specific products, as follows:

Then the customer wants to buy products. Instead of directly contacting the products, he uses the factory, so we have a factory:

Customer through factory buy(type); You can buy the products you want.

This is the simple factory pattern, also known as the static factory method pattern.

If a new product is added, we can write an additional product class Pro3, but we need to add new code in the factory to produce it, which obviously does not comply with the "opening and closing principle (open to extension; closed to modification)", so we abstract the factory and add a specific factory class, and the customer selects a factory, as follows:

When a new product is added, we can create a specific factory to produce it. However, when there are many kinds of products, there will be a large number of corresponding factory objects, which is not what we want.

This is the factory method pattern

When multiple abstractions appear in a product, we may have multiple product interfaces. This scenario becomes what we call

-- Abstract Factory Pattern

Summary:

Whether it is simple factory mode, factory method mode or abstract factory mode, they all belong to factory mode and are very similar in form and characteristics. Their ultimate goal is to decouple. When using, we don't have to care whether this pattern is factory method pattern or abstract factory pattern, because the evolution between them is often elusive. You will often find that the factory method pattern used clearly becomes an abstract factory pattern when new requirements come and a new method is added. Since the products in the class constitute product families in different hierarchical structures, it becomes an abstract factory pattern; For the abstract factory pattern, when a method is reduced so that the provided products no longer form a product family, it evolves into the factory method pattern. Therefore, when using the factory mode, we only need to care about whether the purpose of reducing the coupling degree has been achieved.

The above is an example of Java factory mode. If you have any questions, please leave a message or go to the community of this site for communication and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>