繁体   English   中英

依赖注入:如何访问执行命令的相应 ProductView?

[英]Dependency Injection: How to get access to the corresponding ProductView that executes the Command?

我想为每个产品视图执行命令。 考虑 10 个产品视图,每个视图都可以执行PrintProductViewCommand 此命令接收构造函数ProductView并打印其名称。 由于它@Inject ,每次创建命令时容器都会创建一个新的ProductView。 以下示例显示了我想要做什么:

public class InjectionTest {
    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new AbstractModule() {
            @Override
            protected void configure() {
                bind(ProductView.class);
                bind(CommandExecutor.class);
                bind(PrintProductViewNameCommand.class);
                install(new FactoryModuleBuilder().implement(ProductView.class, ProductView.class)
                        .build(ProductViewFactory.class));
            }
        });

        List<ProductView> productViews = new ArrayList<>();
        ProductViewFactory factory = injector.getInstance(ProductViewFactory.class);
        for (int i = 0; i < 10; i++) {
            productViews.add(factory.create("Name: " + String.valueOf(i)));
        }
        System.out.println("Done creating");
        //Now sometime in future, each product view calls print method
        productViews.forEach(ProductView::print);
    }

    private static interface ProductViewFactory {
        ProductView create(String name);
    }

    private static class ProductView {
        private String name; //simulate a property
        private CommandExecutor executor;

        public ProductView() {
            //Guice throws exception when this is missing
            //Probably because it is being asked in PrintProductViewCommand
        }

        @AssistedInject
        public ProductView(@Assisted String name, CommandExecutor executor) {
            this.name = name;
            this.executor = executor;
        }

        public String getName() {
            return name;
        }

        //assume some time product view it self calls this method
        public void print() {
            executor.execute(PrintProductViewNameCommand.class);
        }
    }

    @Singleton
    private static class CommandExecutor {
        @Inject
        private Injector injector;

        public void execute(Class<? extends Command> cmdType) {
            injector.getInstance(cmdType).execute();
        }
    }

    private static class PrintProductViewNameCommand implements Command {
        private ProductView view;

        @Inject
        public PrintProductViewNameCommand(ProductView view) {
            this.view = view;
        }

        @Override
        public void execute() {
            //Want to print "Name: something" here
            System.out.println(view.getName());
        }

    }

    private static interface Command {
        void execute();
    }
}

如果我向 Command 接口添加一个参数并使其成为Command<T> ,这个问题就解决了。 然后CommandExecutor将有这个方法:

public <T> void execute(Class<? extends Command<T>> cmdType, T parameter) {
    injector.getInstance(cmdType).execute(parameter);
}

所以,我的PrintProductViewNameCommand现在是class PrintProductViewNameCommand implements Command<ProductView> ,在产品视图中:

public void print() {
    executor.execute(PrintProductViewNameCommand.class,this);
}

但是,命令模式execute()中没有参数。 我还在某处看到添加参数是一种反模式。

当然,命令很简单。 假设该命令也有其他依赖项,如服务等。

有什么办法可以实现吗? 也许我做错了什么,可能是整个 DI 情况。

当不使用依赖注入时,我会做这样的事情:

ProductView view = new ProductView();
Command command = new PrintProductViewNameCommand(view);
view.setPrintCommand(command);

但是如何使用 DI 呢?

所以这是有效的,虽然我不确定它是否是你想要做的 100%。

public class InjectionTest {
    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new AbstractModule() {
            @Override
            protected void configure() {
                bind(CommandExecutor.class);
                bind(ProductView.class);
                install(new FactoryModuleBuilder()
                        .implement(ProductView.class, ProductView.class)
                        .build(ProductViewFactory.class));

                install(new FactoryModuleBuilder()
                        .implement(PrintProductViewNameCommand.class, PrintProductViewNameCommand.class)
                        .build(PrintProductViewNameCommand.Factory.class));
            }
        });

        ProductViewFactory factory = injector.getInstance(ProductViewFactory.class);
        List<ProductView> productViews = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            productViews.add(factory.create("Name: " + i));
        }
        System.out.println("Done creating");
        //Now sometime in future, each product view calls print method
        productViews.forEach(ProductView::print);
    }
    private interface ProductViewFactory {
        ProductView create(String name);
    }


    private static class ProductView {
        private String name;
        private CommandExecutor executor;
        private PrintProductViewNameCommand printProductViewNameCommand;

        @AssistedInject
        public ProductView(@Assisted String name, PrintProductViewNameCommand.Factory printProductViewNameCommandFactory, CommandExecutor executor) {
            this.name = name;
            this.executor = executor;
            this.printProductViewNameCommand = printProductViewNameCommandFactory.create(this);
        }

        public ProductView() {}

        public String getName() {
            return name;
        }

        //assume some time product view it self calls this method
        public void print() {
            executor.execute(printProductViewNameCommand);
        }
    }

    @Singleton
    private static class CommandExecutor {
        public void execute(Command command) {
            command.execute();
        }
    }

    private static class PrintProductViewNameCommand implements Command {
        private final ProductView view;

        @AssistedInject
        public PrintProductViewNameCommand(@Assisted ProductView view) {
            this.view = view;
        }

        static interface Factory {
            PrintProductViewNameCommand create(ProductView productView);
        }

        @Override
        public void execute() {
            //Want to print "Name: something" here
            System.out.println(view.getName());
        }

    }

    private static interface Command {
        void execute();
    }
}

基本上你遇到的是一个循环依赖问题( https://github.com/google/guice/wiki/CyclicDependencies#use-factory-methods-to-tie-two-objects-together )也被激怒了事实上,您在ProductView中有一个额外的AssistedInject

顺便说一下,我在此示例中使用的是 Guice 3。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM