Reflection 在返回服务层对象的域包的工厂方法中传递什么对象或类?

Reflection 在返回服务层对象的域包的工厂方法中传递什么对象或类?,reflection,domain-driven-design,factory-method,Reflection,Domain Driven Design,Factory Method,我有一个域包,它有一个名为MyInterface的接口。我还有一个名为MyFactory的工厂类,它应该有助于在运行时创建实现MyInterface的类的实例 域层 interface MyInterface{ //some Domain specific methods here } class MyFactory{ public static MyInterface getInstance(Object resource) { // return MyInterf

我有一个域包,它有一个名为
MyInterface
的接口。我还有一个名为
MyFactory
的工厂类,它应该有助于在运行时创建实现MyInterface的类的实例

域层

interface MyInterface{
    //some Domain specific methods here
}

class MyFactory{
    public static MyInterface getInstance(Object resource) {

    // return MyInterfaceImpl instance via the methods 
    // this Object can also be a Class argument, where I do 
    // Class.forName("").newInstance(); but this is a bad design.
}


class DomainServiceImpl {
    public void domainMethod(Object res) {
        MyInterface i = MyFactory.getInstance(res);
    }
}
服务层

class Class1 implements MyInterface {

}

class Class2 implements MyInterface {

}

class ServiceClass {
    public void service() {
        domainServiceImpl.domainMethod(Object res);
    }
}
因此,我应该如何在域层编写工厂方法,以获得服务层的正确实例,而不使用if/else或switch,并避免循环依赖

选项:可以使用反射,但不确定如何使用

因此,我应该如何在域层编写工厂方法,以获得服务层的正确实例,而不使用if/else或switch,并避免循环依赖

您正在寻找的概念称为“依赖注入”。发表了许多关于这一主题的材料

在域层中,为服务提供者定义接口,并通过构造函数将这些服务提供者注入到实现中

interface MyFactory {
    public MyInterface getInstance(Object resource);
}

class DomainServiceImpl {
    final MyFactory factory;

    // "Dependency Injection"
    public DomainServiceImpl(MyFactory factory) {
        this.factory = factory
    }

    public void domainMethod(Object res) {
        MyInterface i = MyFactory.getInstance(res);
    }
}
然后从外部,您可以实现所需的工厂

class Class1MyFactory implements MyFactory {
    public MyInterface getInstance() {
        return ...;
    }
}
并将其注入服务中的适当点

class ServiceClass {
    final domainServiceImpl;

    public ServiceClass(DomainServiceImpl domainServiceImpl) {
        this.domainServiceImpl = domainServiceImpl;
    }

    public void service() {
        domainServiceImpl.domainMethod(Object res);
    }
}
因此,当构建服务时,您可以选择依赖项,然后离开

MyFactory myFactory = new Class1MyFactory(...);
DomainServiceImpl domainServiceImpl = new DomainServiceImpl(myFactory)
ServiceClass service = new ServiceClass(domainServiceImple)

什么是“正确的impl”?什么时候以及根据什么标准做出决定?假设我有不同版本的资源,并且每个版本都有一个impl,那么我想为该资源版本实例化正确的impl。
ServiceClass.service()
从哪里获取资源?您的意思是在不同时间点的源代码版本中的版本吗?服务层与资源层有依赖关系,因此它可以访问资源,但域层没有任何依赖关系。我有点理解您为什么现在提供
res
对象类型。。。但你不会这么做的。域层只涉及域逻辑和数据结构。通常,它只使用内部声明的类型。作为输入,它可以采用基本类型(int、string等)或域类型,但仅此而已。