Factory method pattern for Java design pattern learning

Factory method: define an interface for creating objects, and let subclasses decide which class to instantiate. Factory methods delay instantiation of a class to its subclasses.

Structure diagram of plant method mode:

According to the needs of the project, create a Lei Feng factory. College students can help others, and volunteers can also help others do things.

1: Create a Lei Feng class with the functions of helping others sweep the floor, wash clothes and buy rice.

2: Create a class for college students who learn from Lei Feng and inherit Lei Feng's class to increase their own functions.

3: Create a class of community volunteers and inherit Lei Feng's class.

4: Create a Lei Feng factory interface.

5: Create a factory for college students learning from Lei Feng.

6: Create a volunteer factory to learn from Lei Feng.

7: Test class

8: Console

Buy rice, sweep the floor and wash clothes

Conclusion: simple factory method violates the principle of open and closed, and the factory method overcomes this problem. When new school is needed, for example, when primary school students learn Lei Feng, factory method adds new primary school factories, and then calls can be made in test class.

The factory method pattern also maintains a bit of the flexibility of encapsulating the object creation process. When the object is to be replaced, it can be realized without making changes, which reduces the coupling between the client program and the product object. The factory method pattern is a further abstraction and promotion of the simple factory pattern. Due to the use of polymorphism, the factory pattern preserves the advantages of the simple factory pattern and overcomes its disadvantages. But the disadvantage is that without adding a product, we must add a factory class to increase the additional development volume.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

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
分享
二维码
< <上一篇
下一篇>>