如何制作参数化方法?

时间:2012-02-14 20:35:40

标签: java

我有类似的产品工厂类:

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(){}
        }
    }

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

2 个答案:

答案 0 :(得分:1)

我相信这就是你要找的......

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设为单身。你不需要一个以上,它可以避免很多其他的头痛,你可以这样...... {/ p>

// 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);

答案 1 :(得分:0)

在一个方法中,你可以说它需要一个未知数量的String参数。

Feed构造函数可能是这样的:

public class Feets extends Product {
    private Feets(String... args){
    }
}

参数'args'将是一个String的数组。