Search code examples
javadesign-patternsjavabeans

Java bean instantiation method


This is a question about code structure rather than syntax. I'm building a program with multiple Java bean objects. Java beans have a no parameters constructor. Normally when I want a bean I do

MyBean bean = new MyBean();
bean.setPropertyOne("Foo");
bean.setPropertyTwo("Bar");

If I've got 12 bean types, and I'm continually rewriting versions of the above each time I need a new bean, that seems like a lot of potential redundancy. It would make more sense to have a constructor that takes parameters, but this goes against the Java Bean design pattern. I'm considering that it might make sense to create a distinct data class which has all the Bean creation methods for all the different beans and then get the required bean via that class each time I need it. This would keep the code modular. I could then access the bean as follows:

MyBean bean = myBeanCreationUtility.makeMyBean("Foo", "bar");

What kind of design pattern is commonly used for structing this when your writing software?


Solution

  • Factory pattern is what you are looking for. Check this website that contains several design patterns, including creational ones, like Factory Method or Abstract Factory.