Java Reference
In-Depth Information
type Pattern and role Pattern
The last structural pattern covered in this chapter is not explicitly mentioned as such by the Gang of
Four, but captures a powerful concept that's worth explaining on its own.
The idea is that you will create a level of abstraction above the classes and instances, meaning the
concept of a class is made into a class itself. Each instance of that class, that is, each object, then
represents a different class.
This idea might seem a bit confusing at first. Imagine you're programming an application to man-
age various kinds of products. Like a good object‐oriented programmer, you start out by defining an
abstract Product class and then define concrete subclasses: Book , Movie , Music , and so on. As time
progresses, maybe your product tree becomes more and more complex, and you end up having more
and more subclasses.
Your program is starting to become hard to maintain, with this gigantic product class tree that
keeps growing. This is the typical object‐oriented issue, right? Indeed, subclassing defines an “is a”
relationship, but it's only one way of establishing this conceptual relationship.
You decide to sit back and think about your problem some more. At a basic level, you're trying to
solve a simple concept. You have a set of products you want to manage and that share some particu-
lar attributes and behavior. Each product is of a certain type, a certain class, in your code. What if
you tried to create a class for a class? A class conceptualizing the product type? You set out to try
this idea:
import java.util.Set;
public class ProductType {
private String name;
private Set<String> properties;
public ProductType(String name, Set<String> properties) {
this.name = name;
this.properties = properties;
}
public String getName() {
return name;
}
public Set<String> getProperties() {
return properties;
}
}
import java.util.HashMap;
import java.util.Map;
public class Product {
private double price;
private String name;
private ProductType type;
private Map<String, Object> typeProperties;
 
Search WWH ::




Custom Search