Java Reference
In-Depth Information
public Product(String name, double price, ProductType type) {
this.name = name;
this.price = price;
this.type = type;
this.typeProperties = new HashMap<>();
for (String property : type.getProperties())
this.typeProperties.put(property, null);
}
public double getPrice() {
return price;
}
public String getName() {
return name;
}
public void setProperty(String property, Object value) {
validateProperty(property);
typeProperties.put(property, value);
}
public Object getProperty(String property) {
validateProperty(property);
return typeProperties.get(property);
}
private void validateProperty(String property) {
if (!typeProperties.containsKey(property))
throw new IllegalArgumentException("Property "+property
+" not valid for type: "+type.getName());
}
}
Next, you try it:
import java.util.HashSet;
public class TypeTest {
public static void main(String[] args) {
ProductType musicType = new ProductType("Music",
new HashSet<String>());
ProductType movieType = new ProductType("Movie",
new HashSet<String>());
// Set some properties for books:
ProductType bookType = new ProductType("Book",
new HashSet<String>(){{
add("title");
add("author");
add("pages");
}});
Product someMusic = new Product("A music track", 0.99, musicType);
Product aBook = new Product("My book", 44.99, bookType);
Search WWH ::




Custom Search