Tuesday, February 28, 2006
Creational dependencies and attributes
True extensibility requires a mechanism to handle creational dependencies. Factories are a common design construct to handle those dependencies, but often they don't really remove dependencies: they just concentrate them in a single class.
In C++, thanks to the automatic creation of static objects, it is possible to have self-creating prototypes (or single-product factories), automatically registering themselves in a repository. This is a nice form of Product Trader, a pattern that is often mistaken for a "simple" factory.
In C#, static objects aren't created unless needed, so this approach can't be used. That means we have to resort to other language-specific constructs to have truly extensible software.
Reflection is probably the first idea coming to mind. In C#, creating an object having the class name (as a string) is trivial. However, we probably don't want the product (in the Product Trader terminology) name to be the class name. Therefore, some kind of indirection is needed. This indirection is often realized through a configuration file, which is a good solution in many cases, especially when products will be provided as external plug-ins.
In simpler cases, however, an external file is undesirable. It would be better to simply decorate methods (using .NET attributes) as being factories. A general-purpose, reusable product trader could then discover all the decorated method through reflection, and build a map of product factories. This could be done transparently, the first time the product trader is asked for a product.
I've written code for this reusable, attribute-based product trader under .NET 1.1, and it works like a snap. Now I'm considering building a better version in .NET 2, using generics to increase type safety. Curiously enough, it's not that trivial :-). Anyway, when I'll finish I'll probably write a short paper about it, and post the code here.
Comments:
<< Home
Si vede meglio con un po' di codice sotto il naso :-), magari ad inizio settimana prossima ne posto un po' sul blog e racconto i problemi a renderlo generico, conservando comodita' di uso ma rendendolo piu' type safe...
Post a Comment
<< Home





