gpt4 book ai didi

java - 使用泛型的工厂对象创建者

转载 作者:行者123 更新时间:2023-12-01 14:30:30 26 4
gpt4 key购买 nike

我想用泛型在java中做一个工厂模式。我的代码是:

界面:

public abstract class Factory<T> {
public abstract T create();
}

FactoryA 类:

public class FactoryA extends Factory<FactoryA> {

public FactoryA() {

}

public FactoryA create() {
return new FactoryA();
}

}

FactoryB 类:

public class FactoryB extends Factory<FactoryB> {

public FactoryB() {

}

public FactoryB create() {
return new FactoryB();
}

}

主类:

public class FactoryCreator {

public static <T> T createFactory() {
Factory<T> t = ?; // is that right way?
return t.create();
}

public static void main(String[] args) {
FactoryA factoryA = FactoryCreator.createFactory();
FactoryB factoryB = FactoryCreator.createFactory();
}
}

问题,什么Factory t =需要相等,或者还有其他方法吗?

最佳答案

不太确定您想要实现什么目标,但这可能会有所帮助;

public interface Factory<T> 
{
public T create(String type);
public T create(String type, Object arg);
public T create(String type, Object[] args);
}

然后让一个类实现该工厂接口(interface),如下所示;

public class TemplateFactory<T> implements Factory {

@Override
public T create(String type) throws IllegalArgumentException
{
return create(type, null);
}

@Override
public T create(String type, Object arg) throws IllegalArgumentException
{
// Convert to array of 1 element
Object[] arguments = new Object[1];
arguments[0] = arg;
return create(type, arguments);
}

@Override
public T create(String type, Object[] args) throws IllegalArgumentException
{
// Create array for all the parameters
Class<?> params[] = (args != null) ? new Class<?>[args.length] : new Class<?>[0];
if(args != null)
{
// Adding the types of the arguments
for(int i = 0; i < args.length; ++i)
params[i] = (args[i] != null) ? args[i].getClass() : null;
}

try
{
// Create a class variable
Class classLoader = Class.forName(type);
// Find the right constructor
Constructor co;
if(params.length > 0)
co = classLoader.getConstructor(params);
else
co = classLoader.getConstructor();
// Instantiate the class with the given arguments
T newObject = (T)co.newInstance(args);
return newObject;
}
catch(Exception e)
{
throw new IllegalArgumentException(e.toString());
}
}
}

然后像这样使用它(使用一些想象的策略类作为示例):

TemplateFactory<StrategyInterface> factory;
factory = new TemplateFactory<>();

factory.create("packageName.StrategyA");
factory.create("packageName.StrategyB");
factory.create("packageName.StrategyC");

在此示例中,策略类(A、B 和 C)将实现 StrategyInterface 类。

关于java - 使用泛型的工厂对象创建者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16886990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com