我是一名java初学者,并且对如何最好地构建烹饪程序有疑问。 我有一个名为Ingredient的课程,这个班级目前看起来像这样:
public class Ingredient {
private String identifier;
private double ingredientFactor;
private String titleInterface;
public Ingredient(String identifier, double ingredientFactor,String titleInterface) {
this.identifier = identifier;
this.ingredientFactor = ingredientFactor;
this.titleInterface = titleInterface;
}
我想用一些值作为实例变量初始化几个对象(大约40个)并将它们保存在Map中,例如
Map<String, Ingredient> allIngredients = new HashMap<String, Ingredient>();
allIngredients.put("Almonds (ground)", new Ingredient("Almonds (ground)", 0.7185, "Almonds (ground)");
稍后我想在另一个类中以Map / HashMap的形式检索所有这些对象。 我不确定如何最好地进行,在Ingredient类本身中初始化所有这些对象,或者提供一个初始化它的方法,或者更好地创建一个具有Map with Ingredients的超类(AllIngredients或类似的东西?)作为实例变量?
对任何建议感到高兴,提前谢谢:)
答案 0 :(得分:1)
请不要在Ingredient类本身中初始化所有这些对象。这对于哎呀来说是不好的做法。
只需认为您的类是一个模板,您可以使用该模板创建具有不同属性值的副本(对象)。在现实世界中,如果您的类代表玩具平面的模型,您将使用该模型创建多个玩具平面,但每个玩具平面具有不同的名称和颜色,那么请考虑如何设计这样的系统。你将有一个模型(类)。然后是一个系统(另一个类),用于从不同的颜色和名称选择中获取所需的颜色和名称(如数据库,文件,属性文件)等。
关于你的情况。
另请查看以下链接
http://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm
http://www.oracle.com/technetwork/java/dataaccessobject-138824.html
答案 1 :(得分:0)
听起来像是在寻找include
。
module MM
module M1
class A
def fun ; puts "module M1 class A method fun()" ; end
end
end
module M2
class A
def fun ; puts "module M2 class A method fun()" ; end
end
end
end
class MyClass
include MM
end
obj1 = MyClass::M1::A.new
puts obj1.class
puts obj1.object_id
obj1.fun
obj2 = MyClass::M2::A.new
puts obj2.class
puts obj2.object_id
obj2.fun
#⇒ MM::M1::A
#⇒ 100355060
#⇒ module M1 class A method fun()
#⇒ MM::M2::A
#⇒ 100354990
#⇒ module M2 class A method fun()