How do I initialize classes with lots of fields in an elegant way?

后端 未结 6 1208
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 11:40

In my application, I have to instantiate many different types of objects. Each type contains some fields and needs to be added to a containing type. How can I do this in an

6条回答
  •  余生分开走
    2020-12-23 12:26

    Ideally, an object should not be concerned about instantiating its dependencies. It should only worry about things that it is supposed to do with them. Have you considered any dependency injection framework? Spring or Google's Juice are quite versatile and have a small footprint.

    The idea is simple, you declare the dependencies and let the framework decide when/how/where to create them and 'inject' it into your classes.

    If you don't want to use any framework, you can take design notes from them and try to emulate their design patterns and tweak it for your use-case.

    Also, you can simplify things to a certain extent by making proper use of Collections. For example, what additional feature does Offers have other than storing a collection of Offer? I'm not sure what your constraints there are but, if you can make that part a bit more cleaner you would have massive gains in all places where you are instantiating the objects.

提交回复
热议问题