aspose file tools*
The moose likes OO, Patterns, UML and Refactoring and the fly likes What is the need for a pattern like factory Pattern? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "What is the need for a pattern like factory Pattern?" Watch "What is the need for a pattern like factory Pattern?" New topic
Author

What is the need for a pattern like factory Pattern?

Hemant Agarwal
Ranch Hand

Joined: Nov 21, 2005
Posts: 138
Why we need factory?
James Clinton
Ranch Hand

Joined: Jun 23, 2003
Posts: 190
It is useful when you know what the parameters of a object will be. As if fixed.

The you can just say give me an object configured as you expected without having to pass in params to the constructor..brilliant.

For example.

// Client to Factory

PersonBean meBean = Factory.getMeBean();

// Factory Class

public static PersonBean getMeBean() {
return new PersonBean("James","Clinton");
}

Imagaine if you had a constructor or 20 params you needed to make an instance of 5 times...this would be a pain, so thats why the Factory Pattern came about. IMHO.
HTH
Hemant Agarwal
Ranch Hand

Joined: Nov 21, 2005
Posts: 138
But I can declare an object with default constructor and then call 20 setter methods.
Sarath PS
Greenhorn

Joined: Oct 22, 2004
Posts: 11
When using factory methods, we don't know the exact class of the object we are creating. What we know is when it should be created and the base class. the actual class instantiated will be depended on so many factors.

The code, that creates the objects, don't want to care about what object is created and how it is created. That responsibility is handed over to the factory, so that the client code can concentrate on it�s (primary ) responsibility. Delegation of responsibility is a good practice(Pattern ? ). Factory pattern encourages this practice.
Mani Ram
Ranch Hand

Joined: Mar 11, 2002
Posts: 1140
Originally posted by Hemant Agarwal:
Why we need factory?


Before I answer that question, can I ask your understanding on this pattern.

AFIK, there is no pattern called as Factory pattern (atleast it is not one of the GoF patterns).
There is an "Abstract Factory" pattern and a "Factory Method" pattern. And there is a "Factory Object" pattern, which is not a part of GoF patterns. There is also another pattern (which some people call as a "Simple Factory"), which many people mistake for the Factory Method.

Which factory are you talking about here?


Mani
Quaerendo Invenietis
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Factory Method and Abstract Factory are basically "polymorphic constructors".


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
That responsibility is handed over to the factory, so that the client code can concentrate on it�s (primary ) responsibility.


I think that pretty much nails it. The benefits include tightening up SRP, reusing the factory instead of repeating the logic throughout the system, and decoupling the caller from the concrete classes that come back.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Hemant Agarwal
Ranch Hand

Joined: Nov 21, 2005
Posts: 138
I have one factory that can create certain objects. Now suppose I want to add one more object to that list. What should I do?
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
That's probably entirely dependent on what your factory already does. If you have client code like

and you modify the factory so that it returns a new widget type then your clients don't have to change at all. That's good news.

On the other hand, that example gives no clue how the factory decides what concrete Widget to return. (That's also good news!) Maybe it uses the day of the week or phase of the moon or a configuration file. The factory is free to extend its current logic to pick a new widget type or completely change its logic.

Is this a concrete question or just exploring the idea some more? Or homework? If you had an example of how your current factory worked we could get into some more solid answers.
sakalareddy tiyyagura
Greenhorn

Joined: Aug 18, 2005
Posts: 2
Can return an object whose implementation class is unknown to the caller; this is a very valuable and widely used feature in many frameworks which use interfaces as the return type of static factory methods.
Do not need to create a new object upon each invocation - caching and reuse of objects are possible have names, unlike constructors, which may make calling code more clear (common names: getInstance, valueOf)
public class ComplexNumber {

public static ComplexNumber valueOf(float real, float imaginary) {
return new ComplexNumber( real, imaginary);
}

//private ctor prevents subclassing
private ComplexNumber ( float real, float imaginary) {
fReal = real;
fImaginary = imaginary;
}

private float fReal;
private float fImaginary;
}
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8919

This article from sun says that there is a creational pattern called as "Factory" pattern. Shouldn't it be "factory method" pattern

http://java.sun.com/developer/JDCTechTips/2006/tt0113.html
A Singleton pattern is often used with another pattern called the Factory pattern. Like the Singleton pattern, the Factory pattern is a creational pattern


Groovy
Hemant Agarwal
Ranch Hand

Joined: Nov 21, 2005
Posts: 138
I have created a factory which is returning some objects.
Now after sometime I have a requirement that my factory should create one more object. I don't want to modify my original factory as it is opposed to the design patterns. Classes should be closed for modification but should be open for extension. What should I do?
Mani Ram
Ranch Hand

Joined: Mar 11, 2002
Posts: 1140
Originally posted by Hemant Agarwal:
Classes should be closed for modification but should be open for extension. What should I do?


While the Open-Closed principle is great, it is impossible to acheive it 100%. Infact trying to apply OCP everywhere, will make the code & design very complex and is often unnecessary.

The biggest advantage of using a factory is that you don't need to make changes to all the calling clients. Hence it can also be viewed as 'the clients are closed for modifications'. You just do the change at a single place and everything continues to work fine.

Ofcourse there are some ways with with you can make the factory to return a new type of object, without even touching the factory (for example, reading the class name from a property file and using the factory to load it dynamically). But the important question is - is such a complexity really required in the first place?
Roger Chung-Wee
Ranch Hand

Joined: Sep 29, 2002
Posts: 1683
But the important question is - is such a complexity really required in the first place?

I'd say yes if you need flexibility in terms of what type you can return. So, you can return any subclass of a declared type and you also have the ability not to create an object each time the factory method is invoked. This is great for immutable objects, otherwise you'd end up unnecessarily creating functionally identical objects. This matters to someone like myself who is always seeking to make his classes immutable.


SCJP 1.4, SCWCD 1.3, SCBCD 1.3
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Pradip Bhat:
This article from sun says that there is a creational pattern called as "Factory" pattern. Shouldn't it be "factory method" pattern

http://java.sun.com/developer/JDCTechTips/2006/tt0113.html


In fact they seem to be mixing Abstract Factory and Factory Method, together with a non-polymorphic creation class (BorderFactory).
Jignesh Patel
Ranch Hand

Joined: Nov 03, 2001
Posts: 626

have created a factory which is returning some objects.
Now after sometime I have a requirement that my factory should create one more object. I don't want to modify my original factory as it is opposed to the design patterns. Classes should be closed for modification but should be open for extension. What should I do?


Yup here you don't need to modify your absctract class where factory pattern defined but you need to modify your Concrete factory class same way you have to create new product class by extending product interface.

Advantage of factory method is you are coding to interface not to concrete class. So other then factory class your internal coding doesn't change.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Classes should be closed for modification but should be open for extension.


An excellent goal! As pointed out above you can't make all classes closed or the system can't change at all. You can think hard about which ones you'd like to be closed and which can be less stable and make deliberate sites of change and other sites of stability.

Robert Martin draws a neat graph of stability vs abstractness. At x=0,y=1 is the least volatile, most abstract. At x=1,y=0 is the most volatile and least abstract (or the other way around). Draw a line between those two points. He suggests classes should gravitate to one end of the line or the other and always fall on the line. A class out a 1,1 would be very abstract (meaning concrete classes depend on it) and a site of change. Ouch.

Does that seem sensible?
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
In http://www.objectmentor.com/resources/articles/ocp.pdf Robert Martin writes:


It should be clear that no significant program can be 100% closed. [...]Since closure cannot be complete, it must be strategic. That is, the designer must choose the kinds of changes against which to close his design. This takes a certain amount of prescience derived from experience. The experienced designer knows the users and the industry well enough to judge the probability of different kinds of changes. He then makes sure that the open-closed principle is invoked for the most probable changes.


And if I remember correctly, in his book "Agile Software Development" (which I can't recommend often enough) he writes something along the lines that it is a valid strategy to wait for the first necessary change to happen, and then to refactor to close the code against similar changes in the future. The reasoning being that one of the best strategies for predicting change is to assume that changes "cluster" - if something needed to change, it's likely that a similar change will happen in the future, too.
 
 
subject: What is the need for a pattern like factory Pattern?