What is factory in java?

Hi,Please tell me what do we mean when we say 'factory pattern', 'conection factory', 'bean factory' etc.Any help is appreciated.Thanks,Rajeev.
[184 byte] By [Rajeev.Asthanaa] at [2007-10-2 22:08:40]
# 1

A factory pattern is a design pattern in which a Factory object has a Factory method that returns an object.

For example, in a Singleton design pattern, an instance is gotten using a factory method:

public class MySingleton {

private MySingleton() // private constructor -- cannot be used outside class.

static private MySingleton instance;

static public MySingleton getInstance() { // This is the factory method. It returns a MySingleton object.

if (instance == null) {

instance = new MySingleton();

}

return instance;

}

}

(note the above code is not thread safe).

Basically, a factory method is an alternative to calling a constructor to get a new object. There are many reasons you may want to do this:

1. To limit access to a constructor, as with the Singleton pattern, to control the number of instances, or to prevent subclassing outside of the package.

2. To cache instances of a similar object, as in the flyweight pattern. (Also, take a look at javax.swing.BorderFactory).

3. To provide "named constructors" (i.e. two different constructors with the same parameters, but different names).

Probably the undisputed authority on the topic would be the Gang of Four book, Design Patterns: Elements of Reusable Object-Oriented Software, by Gamma, et. al.

There's also a decent article in Wikipedia:

http://en.wikipedia.org/wiki/Factory_design_pattern.

For a discussion on the third point, take a look at "Effective Java: Programming Language Guide" by Joshua Bloch. This discussion appears in item 1.

- Adam

guitar_man_Fa at 2007-7-14 1:25:26 > top of Java-index,Java Essentials,New To Java...
# 2

I find the examples at this site: http://www.fluffycat.com/java-design-patterns to be helpful.

The basis for the patterns is a book called "Design Patterns, Elements of Reusable Object-Oriented Software" by 4 authors, Gamma, Helm, etc. http://www.amazon.com/gp/product/0201633612/qid=1149863152/sr=11-1/ref=sr_11_1/103-2440265-9371060?n=283155 It's something you'll definitely want to read to push your OO design skills forward. The examples in this book are in C or C++. If anyone knows of a good book that has been written on design patters with Java examples, please do post a reply.

Basically the factory pattern is used to create objects without specifying their underlying class type. It's a concept I'm still working on grasping. I think an example might be an application that interacts with operating system hardware. The "SoundCard" object may need to be implmented differently for a Mac vs. a PC. So, you would use a SoundCardFactory object to create the sounds, and behind the scenes you wouldn't know if the system was using a MacSoundCard or PCSoundCard object. At least I hope that's a correct example.

Michael_Ebberta at 2007-7-14 1:25:26 > top of Java-index,Java Essentials,New To Java...
# 3
If you're interested in the Factory pattern, you may also want to look into the related Abstract Factory pattern.- Adam
guitar_man_Fa at 2007-7-14 1:25:26 > top of Java-index,Java Essentials,New To Java...
# 4

> Basically the factory pattern is used to create

> objects without specifying their underlying class

> type.

yes, that's true, and according to the gang of four, that is the Main purpose of the pattern, however, the three points I listed above also apply.

- Adam

guitar_man_Fa at 2007-7-14 1:25:26 > top of Java-index,Java Essentials,New To Java...
# 5
I still didn't understand.First off, why it is called Factory? Why it's used? Where it's used?
Rajeev.Asthanaa at 2007-7-14 1:25:26 > top of Java-index,Java Essentials,New To Java...
# 6
> . . . or to prevent subclassing outside of the package.Just checking.Couldn't one accomplish the same thing more simply by just not declaring the constructor[s] as public?
ValentineSmitha at 2007-7-14 1:25:26 > top of Java-index,Java Essentials,New To Java...
# 7

I'm not sure how much more clear I can be.

In reply #1, to quote guitar_man_F:

"Basically, a factory method is an alternative to calling a constructor to get a new object. There are many reasons you may want to do this:

1. To limit access to a constructor, as with the Singleton pattern, to control the number of instances, or to prevent subclassing outside of the package.

So, as regards the comment ". . . or to prevent subclassing outside of the package,

I asked,

Couldn't one accomplish the same thing more simply by just not declaring the constructor[s] as public?

ValentineSmitha at 2007-7-14 1:25:26 > top of Java-index,Java Essentials,New To Java...
# 8

> > . . . or to prevent subclassing outside of the package.

>

> Just checking.

> Couldn't one accomplish the same thing more simply by

> just not declaring the constructor[s] as public?

Sure you could do that but then again your code (outside that package)

needs some public method defined somewhere inside that package to

do the construction for you and that is a factory method again.

A Factory usually uses a bit of 'magic' to get its 'Products' instantiated.

Either by using some configuration data (see the abstract Toolkit

class for a nice example) or by using a two step method where an

abstract Factory creates a concrete factory which you can use.

kind regards,

Jos

JosAHa at 2007-7-14 1:25:26 > top of Java-index,Java Essentials,New To Java...
# 9

Jos,

Thanx for answering my question and, at the same time, showing me how much I still don't know.

I've come across this "factory" stuff several times and it always makes my eyes roll.

I just can't seem to get a handle on what it's all about.

Can you suggest some simple reading for a "Thick as a brick" like me?

ValentineSmitha at 2007-7-14 1:25:26 > top of Java-index,Java Essentials,New To Java...
# 10

> I just can't seem to get a handle on what it's all about.

> Can you suggest some simple reading for a "Thick as a brick"

> like me?

Factories are all about decoupling of classes and code. If an object of

class A directly instantiates an object of class B, A is said to be directly

dependent on B. Suppose I wrote B and you (the creator of A) use my B.

Now we're both stuck: I can't change anything in B without forcing you

to recompile your stuff. You are stuck because when some clever guy

comes up with a C, functionally equivalent to my B, you even have to

change your code again if you want to use C.

This is where those factories come in: that clever guy (who wrote C)

and I agree to make our classes implement the same interface:public interface SomeInterface {

// method declarations here

}

...

public class B implements SomeInterface {

// implementations of those methods here

}

...

public class C implements SomeInterface {

// other implementations of those methods here

}

now I build a simple Factory:public class BFactory implements Factory {

public BFactory() { }

public SomeInterface getProduct() { return new B(); }

}

and that clever guy builds something similar:public class CFactory implements Factory {

public CFactory() { }

public SomeInterface getProduct() { return new C(); }

}

Both factories are *concrete* factories, i.e. they both create concrete

objects and just expose the implemented interface of those object.

Your code doesn't benefit much from all this structural hullabaloo but

note that those factories implement a same interface too:public interface Factory {

SomeInterface getProduct();

}

Lets construct another factory that returns a Factory (the interface). The

strategy *which* Factory is returned depends on a bit of 'magic'. Maybe

some property settings could determine what Factory to return, maybe

some JNDI entry determines it; who cares. This is the AbstractFactory:public abstract class AbstractFactory {

private AbstractFactory() { }

//

public static Factory getFactory() {

if (<some mumbo jumbo here ...>)

return new BFactory();

else

return new CFactory();

}

}

Now all your code has to do is:

1) get a Factory from this AbstractFactory

2) get a SomeInterface product from that factory

like this:SomeInterface i= AbstractFactory().getFactory().getProduct();

... and use it as before. Your code doesn't know what was really returned

to you but you could use it according to the contract of the SomeInterface.

Me and that clever guy can happily code along because noone depends

on our actual class definitions anymore and all live happily ever after ;-)

For a more thorough explanation I do refer to the GoF book again.

kind regards,

Jos

JosAHa at 2007-7-14 1:25:26 > top of Java-index,Java Essentials,New To Java...
# 11
I'm going to print a large font copy, lay in my hammock, and read.But first, I wanted to thank you very large for taking that time.If you're ever in my neighborhood (mid-Atlantic USA), let me know.ValentineSmith@comcast.NET
ValentineSmitha at 2007-7-14 1:25:26 > top of Java-index,Java Essentials,New To Java...
# 12

> I'm going to print a large font copy, lay in my hammock, and read.

> But first, I wanted to thank you very large for taking that time.

You're welcome of course; I'm, sitting in my back garden too, lurking and

writing a bit and working a bit. It's in the mid nineties (Fahrenheit)

overhere at the moment and sunny all over the place.

> If you're ever in my neighborhood (mid-Atlantic USA), let me know.

Thanks for the invitation but don't expose your email address like that.

You don't fancy viagra, hoodia, cheapest mortgages, Nigerian capital,

penile extending or unreadable Brasilian spam do you? ;-)

kind regards,

Jos

JosAHa at 2007-7-14 1:25:26 > top of Java-index,Java Essentials,New To Java...
# 13

> > . . . or to prevent subclassing outside of the

> package.

>

> Just checking.

> Couldn't one accomplish the same thing more simply by

> just not declaring the constructor[s] as

> public?

that's part of it. But then you wouldn't be able to instantiate the objects outside of the package. That's where the public factory method comes in.

- Adam

guitar_man_Fa at 2007-7-14 1:25:26 > top of Java-index,Java Essentials,New To Java...