Reputation: 2801
I have similar class for making Product factory:
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(){}
}
}
This factory makes list of products using size of animals. But I also need to parameterize method/class that I will set type of product, for exampe new Feets (using parameters of constructor). How can I do it? Thank you.
Upvotes: 0
Views: 129
Reputation: 6179
I believe this is what you're looking for....
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;
}
And then you can call like this....
// Assuming you want a Feet object....
Feet feet = productFactoryInstance.getNewProduct(Feet.class, "productParam1", productParam2);
Also, as a side note, you should make your ProductFacotry a singleton. You don't need more than one and it avoids a lot of other head aches, you can to this like so....
// 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;
}
And then, whenever you want to use it to get a product, just do this....
Feet feet = ProductFactory.Get().getNewProduct(Feet.class, "productParam1", productParam2);
Upvotes: 1
Reputation: 26
In a method you can say that it takes a unknwn number of String parameters.
The Feed constructor may be something like this:
public class Feets extends Product {
private Feets(String... args){
}
}
The argument 'args' will be an array of String's.
Upvotes: 0