Design Pattern - Factory Method

G

Guest

I am using the factory method to solve a problem where a factory can produce
product.
I have a base factory class and a base product class. The problem that I am
having is that for every product subclass type I am having to create a
factory subclass to handle differences in logic. They are becoming one to
one. Is this ok? Should I look at another pattern to solve the problem?

abstract Product
Product1: inherits Product
Product2: inherits Product

abstract Factory
Factory1: inherits Factory
Factory2: inherits Factory


abstract class Factory
{
public Product Generate()
{
throw new System.NotImplementedException();
}
}



public class Factory1: Factory
{
}

public class Factory2 : Factory
{
}


abstract class Product
{
}

public class Product1: Product
{
}

public class Product2 : Product
{
}
 
K

Kevin Spencer

I am using the factory method to solve a problem where a factory can
produce
product.
I have a base factory class and a base product class. The problem that I
am
having is that for every product subclass type I am having to create a
factory subclass to handle differences in logic. They are becoming one to
one. Is this ok? Should I look at another pattern to solve the problem?

To solve what problem? You didn't mention what problem you're trying to
solve.

In any case, what you're doing is basically an implementation of the Factory
pattern. The abstract Factory class is derived to create various Factories
that produce derivations of the abstract Product class. There is one problem
with your sample code, however:
abstract class Factory
{
public Product Generate()
{
throw new System.NotImplementedException();
}
}

The Generate method should be abstract. The purpose of the base class is
(primarily) to provide a common interface for clients to generate products.
Making the Generate method abstract enforces that this is the method to
create a Product. At the very least it should be virtual, so that it CAN be
overridden. But abstract in the specific example you've provided would be
correct, since your base Product class is abstract, and cannot be
implemented directly.

--
HTH,

Kevin Spencer
Microsoft MVP

Printing Components, Email Components,
FTP Client Classes, Enhanced Data Controls, much more.
DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net

Eric said:
I am using the factory method to solve a problem where a factory can
produce
product.
abstract class Factory
{
public Product Generate()
{
throw new System.NotImplementedException();
}
}
<snip>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top