Using templates to switch interface implementation class
Marcin Kuszczak
aarti at interia.pl
Sun May 21 10:42:48 PDT 2006
Hello!
I tried to intelligently change implementation class. What do I mean by
intelligently? Here are my requirements:
1. It should be possible to change every implementation separately not by
using some global switch.
2. It is not necessary to switch implementation classes on runtime.
3. Program should use configuration file (in d language) to store
information about which implementation classes should be used.
4. It seems that it would be good idea to bind interface name with concrete
implementation class in above mention configuration class.
Above requirements were fullfilled in C++ program which we write in our
company. Such an architecture was necessary to abstract from concrete view
classes (MFC) and use special test classes intstead. Solution is done using
templates and some macro magic and is a little bit hackish, but anyway
works just good.
In configuration file you just write sth. like this:
#include "mainviewtest.h"
BIND_INSTANCE(IMainView, MainViewTest);
and in code you use factory with templates to instantiate implementation
class.
My question is how to achieve same effect in D?
---
I tried to prepare sth. what partially works, but is still not enough. Below
you can find (working only for one binding) solution.
------------------------
main.d:
import instancefactory;
import imainview;
void main() {
IMainView mv=(new ViewFactory!(IMainView)).getInstance();
mv.forward();
mv.showList();
}
------------------------
imainview.d:
module imainview;
interface IMainView {
public void forward();
public void showList();
public void getData();
}
------------------------
instanceconfig.d:
module instanceconfig;
template Bind(I, T) {
alias T PT;
template getInstance(MI:I) {
MI getInstance() {
return new PT;
}
}
}
import vcards.uiview.model.imainview;
import vcards.uiview.test.mainview_test;
import vcards.uiview.impl.mainview;
mixin Bind!(IMainView, MainViewTest);
--
Regards
Marcin Kuszczak
(Aarti_pl)
More information about the Digitalmars-d-learn
mailing list