473,397 Members | 1,960 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

How to approach constructing an instance of an unknown class?

I have a class that reads an XML and
according to its contents, it creates a
List<Letter>, where Letter is an abstract
class that is implemented in Alpha and
Beta classes.

I use a foreach statement consisting of a
switch upon which i create an instance of
e.g. Alpha an add it to the list.

The only limitation is that if i ever
invent a new implementation, say Gamma,
i'll be forced to rewrite, recompile and
reinstall the executable.

I'm looking for a suggestion on how to
approach the problem so that a new type
will be handled appropriately (provided
that i distribute SOME definition of the
appropriate actions to be taken).

--
Regards
Konrad Viltersten
----------------------------------------
May all spammers die an agonizing death;
have no burial places; their souls be
chased by demons in Gehenna from one room
to another for all eternity and beyond.
Sep 4 '08 #1
6 1638
You could have an app.config file

<classes>
<add key="Alpha" value="MyNameSpace.MyClass, MyAssemblyName"/>
<add key="Beta" value="MyNameSpace.MyClass2, MyAssemblyName"/>
<add key="Gamma" value="MyNameSpace.MyClass3, NameOfMyNewAssembly"/>
</classes>

You can read these in and add them to a Dictionary<string, Type>, then you
can easily create instances based on the name. This way you can drop a new
DLL into the folder + update the app.config and you are all done.

Pete

Sep 4 '08 #2

"K Viltersten" <tm**@viltersten.comwrote in message
news:6i************@mid.individual.net...
>I have a class that reads an XML and
according to its contents, it creates a
List<Letter>, where Letter is an abstract
class that is implemented in Alpha and
Beta classes.

I use a foreach statement consisting of a
switch upon which i create an instance of
e.g. Alpha an add it to the list.

The only limitation is that if i ever
invent a new implementation, say Gamma,
i'll be forced to rewrite, recompile and
reinstall the executable.

I'm looking for a suggestion on how to
approach the problem so that a new type
will be handled appropriately (provided
that i distribute SOME definition of the
appropriate actions to be taken).
Sounds like a classic case for the abstract factory pattern. For instance,
let's say that you decide on the class to use depending on the name of the
XML element that you encounter. Then, you abstract away the logic of
creating a letter of specific type from an XML node as a delegate (or an
interface), and introduce a registry (could be one, could be several) for
known implementations of that interface/delegate.

delegate Letter LetterFactory(XElement element);
Dictionary<XName, LetterFactoryFactories;

List<LetterParseLetters(XDocument document)
{
XElement current;
...
var factory = Factories[current.Name];
var letter = factory(current);
...
}

...

Alpha AlphaLetterFactory(XElement element)
{
Alpha result = ...; // create and fill from XML
return result;
}

Factories.Add("alpha", AlphaLetterFactory);

...

Beta BetaLetterFactory(XElement element)
{
Beta result = ...; // create and fill from XML
return result;
}

Factories.Add("beta", BetaLetterFactory);

...

XDocument doc = ...;
ParseLetters(doc);
Sep 4 '08 #3
>>I have a class that reads an XML and
>according to its contents, it creates a
List<Letter>, where Letter is an abstract
class that is implemented in Alpha and
Beta classes.

I use a foreach statement consisting of a
switch upon which i create an instance of
e.g. Alpha an add it to the list.

The only limitation is that if i ever
invent a new implementation, say Gamma,
i'll be forced to rewrite, recompile and
reinstall the executable.

I'm looking for a suggestion on how to
approach the problem so that a new type
will be handled appropriately (provided
that i distribute SOME definition of the
appropriate actions to be taken).

Sounds like a classic case for the abstract factory pattern. For instance,
let's say that you decide on the class to use depending on the name of the
XML element that you encounter. Then, you abstract away the logic of
creating a letter of specific type from an XML node as a delegate (or an
interface), and introduce a registry (could be one, could be several) for
known implementations of that interface/delegate.

delegate Letter LetterFactory(XElement element);
Dictionary<XName, LetterFactoryFactories;

List<LetterParseLetters(XDocument document)
{
XElement current;
...
var factory = Factories[current.Name];
var letter = factory(current);
...
}

...

Alpha AlphaLetterFactory(XElement element)
{
Alpha result = ...; // create and fill from XML
return result;
}

Factories.Add("alpha", AlphaLetterFactory);

...

Beta BetaLetterFactory(XElement element)
{
Beta result = ...; // create and fill from XML
return result;
}

Factories.Add("beta", BetaLetterFactory);

...

XDocument doc = ...;
ParseLetters(doc);
Oh, i think i see the approach. Only one
question, regarding the var keyword. Is
it allowed even in DotNet 2.0? I fear
that it's a newer thing, like 3.0 or 3.5
and such great utilities i can't use. :(

--
Regards
Konrad Viltersten
----------------------------------------
May all spammers die an agonizing death;
have no burial places; their souls be
chased by demons in Gehenna from one room
to another for all eternity and beyond.
Sep 4 '08 #4
Only one
question, regarding the var keyword. Is
it allowed even in DotNet 2.0?
Yes, but it needs C# 3.0 (the language and the .NET library version are
separate). In this case it probably just saves a little typing. The only
*essential* use of var is with anonymous types, which are a C# 3.0 feature.

Marc
Sep 4 '08 #5
K Viltersten <tm**@viltersten.comwrote:

<snip>
Oh, i think i see the approach. Only one
question, regarding the var keyword. Is
it allowed even in DotNet 2.0? I fear
that it's a newer thing, like 3.0 or 3.5
and such great utilities i can't use. :(
"var" is part of C# 3.0, but you can still use it when targeting .NET
2.0 from VS2008. However, it's unnecessary anyway - unless you're using
anonymous types (another part of C# 3.0) you can always just use the
real name instead of "var". It's just the compiler inferring the type
for you.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 4 '08 #6
This approach wont solve the problem you described, in particular

========
The only limitation is that if i ever
invent a new implementation, say Gamma,
i'll be forced to rewrite, recompile and
reinstall the executable.
========
Sep 4 '08 #7

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

Similar topics

18
by: Samuel Kleiner | last post by:
Is there a builtin way of making making another instance of your own class? I really expected type(self)(*args, **keywords) to work this way. Currently i'm doing this: def...
14
by: Arthur | last post by:
A bit inspired by the decorator discussions, I'm trying to tackle something I had been avoiding. Essentially I am trying to create a non-destructive tranformation of an instance of a class - is...
4
by: Earl Teigrob | last post by:
In the exampe below, the constructor of the container class is passed the string called "foo". Within the container class, I would like to create an instance(s) of foo and add them to the ArrayList...
5
by: Brett | last post by:
In a class, I have several Private subs. I declare an instance of the class such as: Dim MySelf as new Class1 within a private sub. The motive is to provide access to other subs within the...
4
by: Ernesto Díaz | last post by:
Hi I need to instance a class at runtime, at runtime I can get the name in a string, i would like to know if its possible to instance the class at runtime with the name in a string. Thanks...
4
by: Tony Johansson | last post by:
Hello! I have a class definition called MyClass see below. I create an instance of this class MyClass I also want this instance to be able to modify the test instance that exist in this...
5
by: JH | last post by:
Hi I found that a type/class are both a subclass and a instance of base type "object". It conflicts to my understanding that: 1.) a type/class object is created from class statement 2.) a...
0
by: mkadasi | last post by:
I want to dynamically create instance of class stored in other application. I am writing the following code for this purpose: Here in the AssemblyFunc() I am loading the assembly of TariffClass...
1
by: rythmic | last post by:
Hi! PHP is really nifty in the way you can instantiate classes by using string variables like so: $str_class_name = 'User'; $instance = new $str_class_name(); That way you can create...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.