2012-02-14 31 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); 
相關問題