View Single Post

  #3 (permalink)  
Old 10-24-2003, 08:19 AM
Pradyumn Sharma
Guest
 
Posts: n/a
Re: Factory design pattern Vs abstract factory design pattern

nimmi_srivastav@yahoo.com (Nimmi Srivastav) wrote in message news:<8b0c42d.0310230728.252a4ffe@posting.google.com>...
> Hi,
>
> Can anyone kindly help me to understand, once and for all, the
> difference between the Factory design pattern and the Abstract Factory
> design pattern, as discussed in the GoF book.
>
> Are there enough differences between the two to warrant including both
> of them as separate patterns altogether.
>
> Regards,
> Nimmi


If there is only one creator, it specifies an abstract factory method,
allowing its subclasses to choose the concrete product to instantiate.

interface Product {
// ...
}

class Product1 implements Product {
// ...
}

abstract class Creator {
someMethod () {
// ...
Product prod = createProduct ();
// ...
}
abstract Product createProduct ();
// ...
}

class Creator1 extends Creator {
Product createProduct () {
return new Product1 ();
}
// ...
}

However, if there are multiple creators in the application, which want
to create these products, we may end up duplicating these factory
methods in all of them. For example:

abstract class someOtherCreator {
someOtherMethod () {
// ...
Product prod = createProduct ();
// ...
}
abstract Product createProduct ();
// ...
}

class someOtherCreator1 extends someOtherCreator {
Product createProduct () {
return new Product1 ();
}
// ...
}

We can avoid this duplication of the factory methods in two (or more)
creator hierarchies, by factoring out these factory methods in a
separate class.

abstract class Factory {
public abstract Product createProduct ();
}

class Factory1 extends Factory {
public Product createProduct () {
return new Product1 ();
}
}

class Creator {
private Factory factory;
public Creator (Factory f) {
factory = f;
}
someMethod () {
// ...
Product prod = factory.createProduct ();
// ...
}
// ...
}

class someOtherCreator {
// ... calling factory.createProduct, like in Creator class above.
}

Hope this helps.

Pradyumn Sharma
www.pragatisoftware.com
Reply With Quote