编译时的工厂模式 [英] Factory pattern for compile time
问题描述
我正在尝试解决此问题的正确设计
I am trying to figure out the right design for this problem
我有线程,消费者和事件三类
I have three classes Thread, Consumer, and Event
public class Thread {
private Consumer _consumer = new Consumer();
}
public class Consumer {
private someMethod() {
Event event = new Event();
// do something with event
}
}
In创建了我的主 T,并封装了其依赖项
In my "main" T is created and its dependencies are encapsulated
Thread t = new Thread();
现在设计已更改,我们需要多个 Consumer
和它们每个都应构造一个不同的 Event
。所有人的代码都是相同的,所以我不需要更改 Consumer
。
Now the design has changed and we need multiple Consumer
s and each one of them should construct a different Event
. The code is same for all so I don't need to change Consumer
.
我尝试使用泛型,看起来像是一种简单干净的方法。但是,似乎无法在泛型类型上使用 new 。
(受C ++模板误导)
I tried to do it with generics, as it looks like this is a simple and clean way. However, it looks like it is not possible to use new on generic type. (Misguided by C++ templates)
public class Thread<T extends Event> {
private Consumer _c = new Consumer<T>();
}
public class Consumer<T extends Event> {
private someMethod() {
Event event = new T();
}
}
我的另一个选择是经过某种编译时间factory
My other option is to pass some kind of compile time factory
public interface IEventFactory {
public Event create();
}
public class EventFactory implements IEventFactory{
public Event create() {
return new Event1();
}
}
public class Thread {
private Consumer _consumer;
public Thread (IEventFactory _factory) {
_consumer = new Consumer(_factory);
}
}
public class Consumer {
private IEventFactory _factory;
public C(IEventFactory factory) {
_factory = factory;
}
private someMethod() {
Event event = _factory.create();
}
}
此解决方案在通过工厂的过程中感觉不太优雅下。
是否有更好,更优雅的方法来解决这个问题?
This solution feels less elegant passing the factory all the way down. Is there a better and more elegant way approaching this?
推荐答案
工厂在这里只添加了样板。您可以使用方法引用来完成同一件事:将 Event
的构造函数传递给 Consumer
的构造函数。使用 供应商
功能接口。
The factory is adding nothing but boilerplate here. You can accomplish the same thing with a method reference: pass the Event
's constructor into Consumer
's constructor. Use the Supplier
functional interface to do this.
public class Consumer<T extends Event> {
private final Supplier<T> eventConstructor;
public Consumer(final Supplier<T> eventConstructor) {
this.eventConstructor = eventConstructor;
}
private void someMethod() {
final T event = eventConstructor.get();
}
}
您可以从线程
:
class Thread<T extends Event> {
private Consumer<T> consumer;
public Thread(final Supplier<T> eventConstructor) {
this.consumer = new Consumer<>(eventConstructor);
}
}
示例用法:
Thread<Event1> thr = new Thread<>(Event1::new);
如果某些事件具有构造函数参数,这也将起作用,例如:
This will also work if certain events have constructor parameters, for example:
Thread<Event2> thr2 = new Thread<>(() -> new Event2("some default"));
这篇关于编译时的工厂模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!