2012-02-14 33 views
0

我也有类似的类产品制造工厂:如何制作参数化方法?

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(使用构造函数的参数)。我该怎么做?谢谢。

+0

我觉得我可以帮你,但我不明白你的问题。我没有看到你的构造函数的参数。如果您事先了解它们,那么您可以简单地将它们从您的工厂传出。如果您事先不知道该参数,则必须在运行时通过传递类参数来告诉您哪种类型。 – 2012-02-14 20:48:55

回答

0

在一种方法中,你可以说它需要一个不带数量的字符串参数。

饲料构造可以是这样的:

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

参数“ARGS”将字符串的数组。

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是一个单身人士。你并不需要一个以上的,它避免了很多其他的头痛的,你可以这样像这样....

// 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); 
相关问题