gpt4 book ai didi

java - 如何制作参数化方法?

转载 作者:行者123 更新时间:2023-12-01 15:33:20 25 4
gpt4 key购买 nike

我有类似的类来制作产品工厂:

package com.nda.generics;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.nda.generics.Sizeable.Size;

public class ProductFactory{

private Collection<? extends Sizeable> sources;

public ProductFactory(Collection<? extends Sizeable> sources) {
this.sources=sources;
}

public void setSources(Collection<? extends Sizeable> sources) {
this.sources=sources;
}

public Collection<Product> makeProductList() {

Collection<Product> products=new ArrayList<Product>();

for (Sizeable item:sources) {

switch(item.getSize()) {

case BIG: products.add(new Sausage()); break;
case MIDDLE: products.add(new Feets()); break;
case LITTLE: products.add(new Conservative()); break;
}
}

return products;
}

public class Conservative extends Product {

private Conservative(){}
}

public class Feets extends Product {

private Feets(){}
}

public class Sausage extends Product {

private Sausage(){}
}
}

这家工厂使用动物的大小制作产品 list 。但我还需要参数化我将设置产品类型的方法/类,例如新的脚(使用构造函数的参数)。我该怎么做?谢谢。

最佳答案

我相信这就是您正在寻找的......

public <T extends Product> T getNewProduct(Class<T> productClass, String param1, int param2) {

T product = productClass.newInstance();

// Assuming your abstract Product class defines these setters
product.setStringParam(param1);
product.setIntParam(param2);

return product;
}

然后你就可以这样调用......

// Assuming you want a Feet object....
Feet feet = productFactoryInstance.getNewProduct(Feet.class, "productParam1", productParam2);

此外,作为旁注,您应该将 ProductFacotry 设置为单例。你不需要多个,它可以避免很多其他的头痛,你可以像这样......

// Make ProductFacotry constructor private so you don't call "new" all over the place
private ProductFactory() {}

// Variable to hold your only instance of product factory (hence, singleton name...)
private static ProductFactory INSTANCE = null;

public static synchronized Get() {
if(INSTANCE == null) {
// You can call the constructor here, even though its private since you're
// inside the same class
INSTANCE = new ProductFactory();
}

return INSTANCE;
}

然后,每当您想使用它来获取产品时,只需执行此操作...

Feet feet = ProductFactory.Get().getNewProduct(Feet.class, "productParam1", productParam2);

关于java - 如何制作参数化方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9283810/

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