Default Implementation For an Interface

Kevin kevincox.ca at gmail.com
Thu Feb 16 04:47:18 PST 2012


> As a user (read developer), I'd rather code to the generic interface 
> when possible. I like that concrete implementations looks rather long 
> and ugly
> I don't think you should be worried that your users is using direct 
> implementations rather than the interface - their problem!
>
> Remember that in D, interfaces can contain implementations that only 
> uses static methods on the interface:
>
> interface DB {
>     @property string name();
>     // interfaces can have implementations
>     static DB createDefault() { return new GenericDB(); }
> }
>
> class GenericDB : DB {
>     @property string name() {
>         return "generic"; }
> }
>
> class MySQLDB : DB {
>     @property string name() {
>         return "mysql"; }
> }
>
> void main() {
>     assert(DB.createDefault().name == "generic");
>     assert((new MySQLDB()).name == "mysql");
> } 

I see what you are saying.  If it is not possible to have a default I 
think I will call the interface Database and the class BasicDatabase as 
that sounds intuitive.

Thanks to everyone for the help.


More information about the Digitalmars-d-learn mailing list