java对象层次结构
零售店的正确模式是什么?e、 g.公司从商店销售产品
一家公司可以有许多商店,销售许多产品。这些产品不一定与每家商店都有关联,或者我会这么想
我有一项基本任务,要求我设计一个计算产品经济订单数量的系统。我们应该实施一个适用于以后任务的结构(我们没有详细说明),建议的结构如下:
public class Company {
private Store store;
public static void main(String[] args)
{
Store storeOne = new Store();
storeOne.setEOQRelevantValues(1, etc..);
}
}
public class Store {
private Product product;
//..
public setEOQRelevantValues(int eoqRelevantValues)
{
Product.setEOQRelevantValues(eoqRelevantValues);
}
}
public class Product{
private int eoqRelevantValues;
//..
public setEOQRelevantValues(int eoqRelevantValues)
{
this.eoqRelevantValues = eoqRelevantValues;
}
public int calculateEOQ()
{
//do stuff with this.eoqRelevantValues..
return EOQ;
}
}
这似乎违背了我对OOP所知的一切。通过层次结构向下传递数据的方法——在对象之间复制参数?我错过了什么
# 1 楼答案
您应该担心,通过自上而下传递所有参数来初始化对象的层次结构是不常见的
你的讲师可能暗示你按照复合模式实现了一些东西,层次结构中的每个类共享一个公共方法(例如^{)。在
Product
(即叶节点)的情况下,这将简单地返回乘积的值,而在Store
或Company
的情况下,它将在组成Product
(或Store
)上迭代,调用getValue()
并对结果求和这与您上面所写内容之间的关键区别在于,您通常会通过其构造函数分别初始化每个
Product
,而不是通过从另一个对象传递数据。如果产品是不可变的,您可以选择将其字段标记为final
。然后,您可以选择将实用程序方法添加到层次结构中的其他类(例如moveProduct(Store store1, Store store1)
);换句话说,其他类将表现出行为,而不仅仅是“数据容器”示例