Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

java - Motivation for Simple Factory and Factory Method Pattern

I know there are a lot of questions out there about differences of different factory patterns, but the answers are so different and confusing. The books that i read use unclear and (over)simplified examples. I have a number of questions even after reading Wikipedia explanations, and a lot of online explanations about them including all on these site. The book that I'm currently reading is Head First Design Patterns.

In Simple Factory the client uses separate class (Creator) with factory method (which CAN be static) to return Products.

In Factory Method Pattern the Creator and the Client are the same thing and they use abstract method in the same class to create new Products, on which they operate in that same class. Of course the Creator (or Client) are abstract, so the decision about making the Concrete Product is deferred to sub-classes.

  1. Is my understanding correct (for ex. are the Client and Creator in FMP the same thing, I never see Client in FMP diagram)?

  2. In Factory Method Pattern it seams that the create method is not reusable outside of the Creator, so it can only be reused when making some new Creator?

  3. What are the situations where I can choose one over the other?

(P.S. Please don't mark this as duplicate, I want to make this thing clear on this site)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Simple Factory is a factory in the form of a class. Because of that it doesn't solve the problem with elegance, since for every new subclass of Product you will have to edit the switch statement in the create() method. This is a violation of the Open/Close Principle. A potential way to make a Simple Factory useful would be to use class registration as sawn here: http://www.oodesign.com/factory-pattern.html

Factory Method is a factory in the form of a method (hence the name). This doesn't violate the Open/Close Principle since you deal with change by extending and not by modifying code.

Your understanding is correct. Client and Creator/Factory in FMP are the same since the Factory (method) is part of the Client.

It is true that the create method in FMP is not reusable. That is ok though, because this is not an attempt to create an application-wide Factory of the Product, but a way for the Client to create his depended objects without using new.

I cannot answer you third question since I believe it is based on preference.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...