473,246 Members | 1,491 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,246 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 1633
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...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.