Java Reference
In-Depth Information
In conclusion, the type pattern is a very powerful one, and it allows you to create your own object‐
oriented paradigm inside an existing one (object‐oriented inception). Some warning, however—you
will have noticed that this pattern is especially useful when you're dealing with shared data , that is,
a list of properties for product types.
Note that this pattern's implementation will change a bit when you know up front what the set of
properties will be. In that case, just implement this as follows:
The fields you want to change at runtime can be implemented as fields in the class ( Product ,
for instance). Fields that are not necessary for a certain product can be set to null .
The fields that are determined by the type are implemented as fields in the type class and set
at construction or by setters (e.g., in ProductType ). Getters are added to the original class
( Product ) to fetch information from the type class ( ProductType ), or the type object is
directly exposed ( getProductType() in Product ).
Note that all of this still has to do with data. When you also want to dynamically construct behavior ,
things get much more difficult. You're then better off resorting to subclasses, or you can apply the
strategy pattern (which you'll see later) to dynamically assign another object to your type class from
which a method will be called to execute some behavior. As a simple teaser, consider, for example,
that you want to implement a method that calculates a discounted price. Sadly, the way this discount
is calculated can differ for each product type. In this case, you need to get a bit clever when assigning
properties and their values. Why not go a step further as well? The product manager above was basi-
cally assuming that all fields in a product type are non‐static, non‐final, public, and uninitialized. You
can change your type class and allow for static final properties that are all public:
import java.util.HashMap;
import java.util.Map;
public class ProductType {
private String name;
private Map<String, Object> staticProperties;
private Map<String, Object> instanceProperties;
public ProductType(String name) {
this.name = name;
this.staticProperties = new HashMap<>();
this.instanceProperties = new HashMap<>();
}
public Product createProduct(String name, double price) {
return new Product(name, price, this);
}
public String getName() {
return name;
}
public void addStaticProperty(String name, Object value) {
staticProperties.put(name, value);
}
Search WWH ::




Custom Search