Java:在类本身中创建多个对象实例或如何重构

时间:2015-04-30 07:31:51

标签: java class object structure

我是一名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或类似的东西?)作为实例变量?

对任何建议感到高兴,提前谢谢:)

2 个答案:

答案 0 :(得分:1)

请不要在Ingredient类本身中初始化所有这些对象。这对于哎呀来说是不好的做法。

只需认为您的类是一个模板,您可以使用该模板创建具有不同属性值的副本(对象)。在现实世界中,如果您的类代表玩具平面的模型,您将使用该模型创建多个玩具平面,但每个玩具平面具有不同的名称和颜色,那么请考虑如何设计这样的系统。你将有一个模型(类)。然后是一个系统(另一个类),用于从不同的颜色和名称选择中获取所需的颜色和名称(如数据库,文件,属性文件)等。

关于你的情况。

  1. 如果预定值将值存储在文本文件中,则属性文件,数据库,类中的常量等取决于数据的敏感性。
  2. 使用构造函数创建成分类
  3. 创建一个类,该类将具有使用预定值初始化Ingredient类的方法,如果需要更新值,将值保存到文本文件-database等,并在您的情况下返回为map。
  4. 另请查看以下链接

    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()