Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

design patterns - Factory, Abstract Factory and Factory Method

I am really confused about these three terms.

My understanding is that:

  • in the Factory pattern, there is no concrete factory. The factory builds the new objects according to the parameters.

  • in Abstract Factory pattern, there are multiple concrete factories. The client has to create different concrete factories explicitly.

Is that right?

What are the other differences?

Furthermore, what is the Factory Method pattern? Is it same as the Factory pattern?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The Gang Of Four "Design Patterns; Elements of Reusable Object-Oriented Software" book contains two entries, "Abstract Factory" (aka 'Virtual Constructor') and "Factory Method". I don't know about "Concrete Factory." I've heard the term, but never given it too much thought.

Factory Method

In "Factory Method" an object has a method which is responsible for the instantiation of another object. A common example would be the JavaScript document object and the creation of HtmlElement objects:

var newDiv = document.createElement('div');

This isn't a great example though, as an important part of the Factory Method is polymorphism. If I could extend document to define another class which defines another createElement this would be prime Factory Method material.

Abstract Factory

An abstract factory is meant to "provide an interface for creating families of related or dependent objects without specifying concrete classes.

The typical straight-out-of-the-book example is a Widget Factory; back in the day when the GoF was published, cross-platform GUI development was a bit of a hassle, so you could define an abstract widget factory class.

That class could have methods createWindow, createButton, createScrollBar etc. In turn, several implementations would be defined to produce Swing widgets or AWT or whatever. Then, depending on configuration, the different class would be instantiated.

Addendum - Concrete Factory

I believe that a Concrete Factory is any non-abstract implementation of Abstract Factory or Factory method.

So, when I write my own generalization of document which overrides createElement, the class I create is a Concrete Factory.

Likewise, while WidgetFactory would be an Abstract Factory, SwingWidgetFactory would be a concrete factory.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...