How to create a sub-class based on some pre-determined flag.

  • Thread starter Thread starter Wolf
  • Start date Start date
W

Wolf

Say I have the following XML (as example)

<root>
<foo type="num">10</foo>
<foo type="date">2006-10-10</foo>
</root>

I now want to create at run-time a foo object but specifically a
specialisation of it based on the value of the "type" attribute (i.e.
some arbritary value).

What I do currently is,

foo f = null;
if (type == "num"){
f = new fooNum();
}
else if (type == "date"{
f = new fooDate();
}

but...... is there a cleaner way .. more OO?

Can I have some nice way of creating the right subClass based on the
value of the "type" attribute. The XML is just for example but really
what I'm looking for is the correct way of creating subClasses depending
on some condition so that you dont end up using big switch statements!

Ta in advance :-)
 
Wolf wrote:

Can I have some nice way of creating the right subClass based on the
value of the "type" attribute. The XML is just for example but really
what I'm looking for is the correct way of creating subClasses depending
on some condition so that you dont end up using big switch statements!

Look into Type.GetType and Activator.CreateInstance.

Jon
 
Wolf,

You're probably not going to be able to avoid having a piece of custom
somewhere which says ' if the type is A then create fooNum, else create
fooDate'. However, if you're looking for the OO answer to this, I suggest you
look at the creational design patterns, such as the Factory Method, which
delegate responsibility for object creation.

Encapsulated within the factory object, you have a number of options for
creating an instance of your foo object, which Jon has already mentioned. You
could also look into reflection (perhaps storing the Type name to create in
the XML document, and generating the relevant type at runtime).
 
Matt Salmon said:
Wolf,

You're probably not going to be able to avoid having a piece of custom
somewhere which says ' if the type is A then create fooNum, else create
fooDate'. However, if you're looking for the OO answer to this, I suggest
you
look at the creational design patterns, such as the Factory Method, which
delegate responsibility for object creation.

You can create a Dictionary of Factory delegates....
 
Back
Top