您担心的是正确的,因为通过从上到下传递所有参数来初始化对象层次结构是不寻常的。
您的讲师可能暗示您按照复合模式的方式实现某些东西,即层次结构中的每个类共享一个公共方法(例如getValue()
)。在 a Product
(即叶节点)的情况下,这将简单地返回产品的值,而在 a Store
or的情况下,Company
它将遍历组成部分Product
s(或Store
s),调用getValue()
并对结果求和。
这与您在上面编写的内容之间的主要区别在于,您通常会Product
通过其构造函数单独初始化每个对象,而不是通过从另一个对象传入数据。如果产品是不可变的,您可以选择将其字段标记为final
. 然后您可以选择将实用方法添加到层次结构中的其他类(例如moveProduct(Store store1, Store store1)
);换句话说,其他类将表现出行为而不仅仅是“数据容器”。
例子
/**
* Optional interface for uniting anything that can be valued.
*/
public interface Valuable {
double getValue();
}
/**
* Company definition. A company's value is assessed by summing
* the value of each of its constituent Stores.
*/
public class Company implements Valuable {
private final Set<Store> stores = new HashSet<Store>();
public void addStore(Store store) {
this.stores.add(store);
}
public void removeStore(Store store) {
this.stores.remove(store);
}
public double getValue() {
double ret = 0.0;
for (Store store : stores) {
ret += store.getValue();
}
return ret;
}
}
/**
* Store definition. A store's value is the sum of the Products contained within it.
*/
public class Store implements Valuable {
private final List<Product> products = new LinkedList<Product>();
public void addProduct(Product product) {
this.products.add(product);
}
public void removeProduct(Product product) {
this.products.remove(product);
}
public double getValue() {
double ret = 0.0;
for (Product product : products) {
ret += product.getValue();
}
return ret;
}
}
/**
* Product definition. A product has a fixed inherent value. However, you could
* always model a product to depreciate in value over time based on a shelf-life, etc.
* In this case you might wish to change the Valuable interface to accept a parameter;
* e.g. depreciationStrategy.
*/
public class Product implements Valuable {
private final double value;
public Product(double value) {
this.value = value;
}
public double getValue() {
return value;
}
}