473,748 Members | 6,664 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Factory method

I have an abstract class, and a set of classes that inherit from my abstract
class. The fact that it is abstract is likely irrelevant. I have a static
factory method in my abstract class that creates subclasses. The
constructor in my subclasses must be able to call the constructor in my base
class. For the factory method in my abstract class to call the constructor
on my subclasses, the constructor in the subclass MUST be public (or
internal). They cannot be private or protected. However, doen't that
basically defeat the purpose of factory? I'd love to be able to make all
these constructors private or similar so that someone can't create subclass
instances without using the Factory. If this was all in a separate DLL, I
suppose I'd be saved by "internal", but we have small team of developers
working on projects where that type of seperation really shouldn't be
necessary.

Suggestions? Code sample below ...

Thanks in advance.

Mark
public abstract class MyBase
{
protected string first;

public MyBase(string first )
{
this.first = first;
}

public static MyBase Factory(int stateId)
{
switch (stateId)
{
case 700:
return new MySubClass1(fir st);
default:
throw new Exception("Bogu s code!");
}
}
}
Nov 17 '05 #1
10 5139
Well, yes, but then, having the base class have any knowledge at all
it's derived classes defeats the purpose of OO.

--
--
Truth,
James Curran
[erstwhile VC++ MVP]

Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com

"Mark" <Ma**@nowhere.c om> wrote in message
news:uQ******** ******@TK2MSFTN GP09.phx.gbl...
I have an abstract class, and a set of classes that inherit from my abstract class. The fact that it is abstract is likely irrelevant. I have a static
factory method in my abstract class that creates subclasses. The
constructor in my subclasses must be able to call the constructor in my base class. For the factory method in my abstract class to call the constructor on my subclasses, the constructor in the subclass MUST be public (or
internal). They cannot be private or protected. However, doen't that
basically defeat the purpose of factory? I'd love to be able to make all
these constructors private or similar so that someone can't create subclass instances without using the Factory. If this was all in a separate DLL, I
suppose I'd be saved by "internal", but we have small team of developers
working on projects where that type of seperation really shouldn't be
necessary.

Suggestions? Code sample below ...

Thanks in advance.

Mark
public abstract class MyBase
{
protected string first;

public MyBase(string first )
{
this.first = first;
}

public static MyBase Factory(int stateId)
{
switch (stateId)
{
case 700:
return new MySubClass1(fir st);
default:
throw new Exception("Bogu s code!");
}
}
}

Nov 17 '05 #2
check out the definition here

http://www.dofactory.com/Patterns/PatternAbstract.aspx
--
HTH

Ollie Riches
http://www.phoneanalyser.net

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a programmer
helping programmers.

"Mark" <Ma**@nowhere.c om> wrote in message
news:uQ******** ******@TK2MSFTN GP09.phx.gbl...
I have an abstract class, and a set of classes that inherit from my abstract class. The fact that it is abstract is likely irrelevant. I have a static
factory method in my abstract class that creates subclasses. The
constructor in my subclasses must be able to call the constructor in my base class. For the factory method in my abstract class to call the constructor on my subclasses, the constructor in the subclass MUST be public (or
internal). They cannot be private or protected. However, doen't that
basically defeat the purpose of factory? I'd love to be able to make all
these constructors private or similar so that someone can't create subclass instances without using the Factory. If this was all in a separate DLL, I
suppose I'd be saved by "internal", but we have small team of developers
working on projects where that type of seperation really shouldn't be
necessary.

Suggestions? Code sample below ...

Thanks in advance.

Mark
public abstract class MyBase
{
protected string first;

public MyBase(string first )
{
this.first = first;
}

public static MyBase Factory(int stateId)
{
switch (stateId)
{
case 700:
return new MySubClass1(fir st);
default:
throw new Exception("Bogu s code!");
}
}
}

Nov 17 '05 #3
I've been looking at factories today too (as a work-around for the lack of
virtual constructors). It seems that factories work best when the class
doesn't use a parameterized constructor, but has a virtual method to
initialize the new instance. This creates a two-step process:

MyClass x = new MyClass() ;
x.Initialize ( ... ) ;

That first line means that you still need a specialized factory for each
class, yuck.

Ergo, I have devised the following scheme, which has its own shortcomings...

I defined an interface:

public interface IConstructable
{
void Constructor ( params object[] Params ) ;
}

(It sure would be nice if an interface could specify a constructor.)

And the following static factory method:

public static IConstructable
New
(
System.Type What
,
params object[] Params
)
{
IConstructable result = null ;

if ( What.GetConstru ctors().Length > 1 )
{
throw ( new System.Argument Exception ( string.Format
(
"Type {0} contains more than the default constructor."
,
What.Name
) ) ) ;
}

System.Reflecti on.ConstructorI nfo con = What.GetConstru ctor ( new
System.Type[] {} ) ;

if ( con == null )
{
throw ( new System.Argument Exception ( string.Format
(
"Did not find a parameterless constructor for type {0}."
,
What.Name
) ) ) ;
}

if ( !con.IsPublic )
{
throw ( new System.Argument Exception ( string.Format
(
"Did not find a public parameterless constructor for type
{0}."
,
What.Name
) ) ) ;
}

result = (IConstructable ) con.Invoke ( new object[] {} ) ;

result.Construc tor ( Params ) ;

return ( result ) ;
}

Then to use it for a class:

class A : IConstructable
{
private string str ;

public virtual void
Constructor
(
params object[] Params
)
{
this.str = (string) Params [ 0 ] ;
}

public override string
ToString
(
)
{
return ( this.str ) ;
}
}

And to make an instance thereof (this is the fugly part):

A a = (A) New ( typeof(A) , "A" ) ;

This one factory method works with any class that implements IConstructable,
as if 'twere a virtual constructor. But the class's Constructor method will
need to do type checking on the parameters, yuck.

Perhaps I can have it use a struct for the parameters, hmm...

Note that _ideally_ the class would not define a constructor, at most it may
define a public parameterless constructor.

Again, this was to work-around the lack of virtual constructors, so yes, an
uninformed user may call new on the class and mess things up, but I'm still
working on't.
Nov 17 '05 #4
Here's the Flaw
A a = (A) New ( typeof(A) , "A" ) ;
You used 'new'

The point of a factory is that the calling class NEVER uses 'new'

Your design is not a factory. It is interesting. Clever perhaps. I don't
expect to use it.
But it is definitely not a factory.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
"PIEBALD" <PI*****@discus sions.microsoft .com> wrote in message
news:1D******** *************** ***********@mic rosoft.com... I've been looking at factories today too (as a work-around for the lack of
virtual constructors). It seems that factories work best when the class
doesn't use a parameterized constructor, but has a virtual method to
initialize the new instance. This creates a two-step process:

MyClass x = new MyClass() ;
x.Initialize ( ... ) ;

That first line means that you still need a specialized factory for each
class, yuck.

Ergo, I have devised the following scheme, which has its own
shortcomings...

I defined an interface:

public interface IConstructable
{
void Constructor ( params object[] Params ) ;
}

(It sure would be nice if an interface could specify a constructor.)

And the following static factory method:

public static IConstructable
New
(
System.Type What
,
params object[] Params
)
{
IConstructable result = null ;

if ( What.GetConstru ctors().Length > 1 )
{
throw ( new System.Argument Exception ( string.Format
(
"Type {0} contains more than the default constructor."
,
What.Name
) ) ) ;
}

System.Reflecti on.ConstructorI nfo con = What.GetConstru ctor ( new
System.Type[] {} ) ;

if ( con == null )
{
throw ( new System.Argument Exception ( string.Format
(
"Did not find a parameterless constructor for type {0}."
,
What.Name
) ) ) ;
}

if ( !con.IsPublic )
{
throw ( new System.Argument Exception ( string.Format
(
"Did not find a public parameterless constructor for type
{0}."
,
What.Name
) ) ) ;
}

result = (IConstructable ) con.Invoke ( new object[] {} ) ;

result.Construc tor ( Params ) ;

return ( result ) ;
}

Then to use it for a class:

class A : IConstructable
{
private string str ;

public virtual void
Constructor
(
params object[] Params
)
{
this.str = (string) Params [ 0 ] ;
}

public override string
ToString
(
)
{
return ( this.str ) ;
}
}

And to make an instance thereof (this is the fugly part):

A a = (A) New ( typeof(A) , "A" ) ;

This one factory method works with any class that implements
IConstructable,
as if 'twere a virtual constructor. But the class's Constructor method
will
need to do type checking on the parameters, yuck.

Perhaps I can have it use a struct for the parameters, hmm...

Note that _ideally_ the class would not define a constructor, at most it
may
define a public parameterless constructor.

Again, this was to work-around the lack of virtual constructors, so yes,
an
uninformed user may call new on the class and mess things up, but I'm
still
working on't.

Nov 17 '05 #5
The base class should not be bound to the list of possible inheriting
children. The base class must not create the children. That defeats the
purpose.

The child object can have a public constructor. That doesn't mean that you
will use it. If you don't want a public constructor, then define a Factory
Method in the base class and, in the child classes, implement the factory
method to return the object.

You won't be able to "enforce" that the child object cannot have a public
constructor. Why would you want to? But you can provide a mechanism that
the child class must implement that returns an object that derives from the
base type. The users of the class will always use this method, which means
you no longer have to worry about it. If a child class shouldn't have a
public constructor, write it so that the contstructor is private.

The constructor in your subclasses can call the constructor in your base
class. See this topic from Jon's site:
http://www.yoda.arachsys.com/csharp/constructors.html

To implement a factory method, in the base class define an abstract method
that returns an object of the base type.

<Warning -- uncompiled air code>

public abstract myBaseWidget
{
private myBaseWidget(in t myParam)
{
}
public abstract myBase CreateWidget();
}

public myChildWidget : myBaseWidget
{
private myChildWidget() : base(4)
{
// go do constructor things
}
public myChildWidget CreateWidget()
{
// this is your factory method!
return new myChildWidget() ;
}
}

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
"Mark" <Ma**@nowhere.c om> wrote in message
news:uQ******** ******@TK2MSFTN GP09.phx.gbl...
I have an abstract class, and a set of classes that inherit from my
abstract class. The fact that it is abstract is likely irrelevant. I have
a static factory method in my abstract class that creates subclasses. The
constructor in my subclasses must be able to call the constructor in my
base class. For the factory method in my abstract class to call the
constructor on my subclasses, the constructor in the subclass MUST be
public (or internal). They cannot be private or protected. However,
doen't that basically defeat the purpose of factory? I'd love to be able to
make all these constructors private or similar so that someone can't create
subclass instances without using the Factory. If this was all in a
separate DLL, I suppose I'd be saved by "internal", but we have small team
of developers working on projects where that type of seperation really
shouldn't be necessary.

Suggestions? Code sample below ...

Thanks in advance.

Mark
public abstract class MyBase
{
protected string first;

public MyBase(string first )
{
this.first = first;
}

public static MyBase Factory(int stateId)
{
switch (stateId)
{
case 700:
return new MySubClass1(fir st);
default:
throw new Exception("Bogu s code!");
}
}
}

Nov 17 '05 #6
In message <v_************ ********@comcas t.com>, "Nick Malik
[Microsoft]" <ni*******@hotm ail.nospam.com> writes
To implement a factory method, in the base class define an abstract method
that returns an object of the base type.

<Warning -- uncompiled air code>

public abstract myBaseWidget
{
private myBaseWidget(in t myParam)
{
}
public abstract myBase CreateWidget();
}

public myChildWidget : myBaseWidget
{
private myChildWidget() : base(4)
{
// go do constructor things
}
public myChildWidget CreateWidget()
{
// this is your factory method!
return new myChildWidget() ;
}
}


Hmm. How do you create an instance of myChildWidget in order to call the
non-static CreateWidget method?

--
Steve Walker
Nov 17 '05 #7
Some mornings... I write stuff that I am embarrassed to look at later :-}

even 10 minutes later

You are correct, of course. The factory method either has to be static (in
which case, it isn't inherited) or part of another class altogether.

(duh!)
Sorry.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
"Steve Walker" <st***@otolith. demon.co.uk> wrote in message
news:fN******** ******@otolith. demon.co.uk...
In message <v_************ ********@comcas t.com>, "Nick Malik [Microsoft]"
<ni*******@hotm ail.nospam.com> writes
To implement a factory method, in the base class define an abstract method
that returns an object of the base type.

<Warning -- uncompiled air code>

public abstract myBaseWidget
{
private myBaseWidget(in t myParam)
{
}
public abstract myBase CreateWidget();
}

public myChildWidget : myBaseWidget
{
private myChildWidget() : base(4)
{
// go do constructor things
}
public myChildWidget CreateWidget()
{
// this is your factory method!
return new myChildWidget() ;
}
}


Hmm. How do you create an instance of myChildWidget in order to call the
non-static CreateWidget method?

--
Steve Walker

Nov 17 '05 #8
In message <5s************ ********@comcas t.com>, "Nick Malik
[Microsoft]" <ni*******@hotm ail.nospam.com> writes
Some mornings... I write stuff that I am embarrassed to look at later :-}

even 10 minutes later
:O)

Me too.
You are correct, of course. The factory method either has to be static (in
which case, it isn't inherited) or part of another class altogether.


I find that where this happens always a thought-provoking decision.
Polymorphism is great, but at some point you have to bite the bullet and
decide exactly what it is you're going to create an instance of, and it
always seems somehow intellectually unsatisfying. I think the
subconscious appeal of the factory pattern is that you can encapsulate a
bit of code which you'd rather not see :o)

If you can justify taking the hit of using reflection, it's beautiful. I
once wrote a "generic business rules in database" type of system which
instantiated tree structures of rule subclasses by reflection, using
class names from a database. That was neat, but the logic for
determining which class to instantiate is seldom fits so well with that
approach.

--
Steve Walker
Nov 17 '05 #9
Nick Malik [Microsoft] <ni*******@hotm ail.nospam.com> wrote:
Here's the Flaw
A a = (A) New ( typeof(A) , "A" ) ;
You used 'new'

The point of a factory is that the calling class NEVER uses 'new'


And it doesn't - it uses New, which is a method. Note the difference in
case.
Your design is not a factory. It is interesting. Clever perhaps. I don't
expect to use it.
But it is definitely not a factory.


It's not quite the normal factory pattern, but I think it's still a
factory.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
6643
by: Medi Montaseri | last post by:
Hi, Given a collection of similar but not exact entities (or products) Toyota, Ford, Buick, etc; I am contemplating using the Abstraction pattern to provide a common interface to these products. So I shall have an Abstract Base called 'Car' implemented by Toyota, Ford, and Buick. Further I'd like to enable to client to say Car *factory;
2
2979
by: Ryan Mitchley | last post by:
Hi all I have code for an object factory, heavily based on an article by Jim Hyslop (although I've made minor modifications). The factory was working fine using g++, but since switching to the Intel compiler it has stopped working. I think the singleton pattern static instance thing may be at the root of the problem, but I'm not sure. I had to add calls to instance() in regCreateFn, which gets the behaviour more in line with what I was...
4
8240
by: Eric | last post by:
Perhaps this question has been posed before (I'd be surprised if it hasn't) but I just gotta know... Is it possible to combine the Singleton and Factory Method design patterns in the same class? Let's start with your basic Singleton class: class Singleton {
10
1895
by: Chris Croughton | last post by:
What do people call their factory functions? 'new' is not an option (yes, it can be overloaded but has to return void*). The context is: class MyClass { public: // Factory functions static MyClass* new(int);
4
2526
by: max | last post by:
Hello, I analyze this design pattern for a long time but I do not understand how this pattern work and what the purpose is? (I looked a this site http://www.dofactory.com/Patterns/PatternAbstract.aspx). Could anybody try to explain me in his own words how this pattern work and what the purpose is? thanks in advance
8
1767
by: googlegroups | last post by:
Hi, I need to parse a binary file produced by an embedded system, whose content consists in a set of events laid-out like this: <event 1<data 1<event 2<data 2... <event n<data n> Every "event" is a single byte in size, and it indicates how long is the associated "data". Thus, to parse all events in the file, I need to take it like a stream and read one event at a time, consuming bytes
1
1751
by: =?Utf-8?B?RXJpYw==?= | last post by:
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:...
8
1735
by: Steven D'Aprano | last post by:
I'm writing a factory function that needs to use keywords in the produced function, not the factory. Here's a toy example: def factory(flag): def foo(obj, arg): if flag: # use the spam keyword to method() return obj.method(spam=arg) else: # use the ham keyword
4
5015
by: Pallav singh | last post by:
Hi , when should i select Factory Method / Prototype Design Pattern during my design phase ?? as both look similar to me Thanks in Advance Thanks Pallav
0
8987
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8826
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9534
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9316
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4597
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4867
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2777
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2211
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.