www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - I want to implement operation feasible?

reply "Brian" <smartly itbbs.cn> writes:
package com.kerisy.mod.base

interface BaseMod
{
	auto getInstance();
}

package com.kerisy.mod.a

class A : BaseMod
{
	A getInstance()
	{
		return (new A);
	}
	
	void hello()
	{
		// in A
		writeln("in A");
	}
}

package com.kerisy.mod.b

class B : BaseMod
{
	B getInstance()
	{
		return (new B);
	}
	
	void hello()
	{
		// in B
		writeln("in B");
	}
}

import std.stdio;
import com.kerisy.mod.a;
import com.kerisy.mod.b;

int main(string[] argv)
{
	string packageClass;
	
	packageClass packageClass = "mod.forum.controller.forum.A";
	BaseMod modObje = cast(BaseMod)Object.factory(packageClass);
	auto a = modObj::getInstance();
	Object.callMethod(a, "hello");
	
	packageClass packageClass = "mod.forum.controller.forum.A";
	BaseMod modObje = cast(BaseMod)Object.factory(packageClass);
	auto a = modObj::getInstance();
	Object.callMethod(a, "hello");
	
	return 0;
}
Dec 15 2014
parent "Adam D. Ruppe" <destructionator gmail.com> writes:
On Tuesday, 16 December 2014 at 04:45:31 UTC, Brian wrote:
 interface BaseMod
 {
 	auto getInstance();
 }
You can't do that - interface methods must be either final or have concrete types (they can't be templates or auto returns). Make it BaseMod getInstance(); and the rest of your classes will work.
 	auto a = modObj::getInstance();
Since this comes from the interface, a will be typed to the interface too. It will have the dynamic type of the underlying class, but the interface functions will all return the interface. If your hello method is in the interface, you can just call it at that point though and you'll get the results you want. BTW it is modObj.getInstance rather than ::. D always uses the dot.
 	Object.callMethod(a, "hello");
You could write a reflection method like that in D, but it isn't done automatically (partially due to bloat concerns making it opt-in). Check out the free sample of my D book: https://www.packtpub.com/application-development/d-cookbook The free chapter is about D's reflection. I also go into how to make runtime methods like you have in other parts of the book.
Dec 15 2014