cde
cde

Reputation: 187

Building complex object inside or outside the class in Java?

I am trying to get the best practice in Java to solve the following problem :

I want to setup an complex object in one place, so that other clients can then reuse this construction. Here is an example and how I proceed :

My complex object is of type "Ontology", this object contains many parameters, once it is instantiated and filled, it is used in many objects as a kind of configuration by using its getter.

My Ontology.class

abstract class Ontology {
   List<Something1> param1;
   List<Something2> param2;
   ...

   protected void addParam1(){
      ...
   }

   ....

   abstract protected void setup();
}

A way to hold the complex construction :

public class SpecificOntology extend Ontology{          
   @Override
   protected void setup(){
       addParam1(new Something(...));
       ...
   }
}

A client :

 protected void something(){
     SpecificOntology o = new SpecificOntology();
     o.setup();

     install(o.getParam1(());
     ...  
 }

Another solution could be to make Ontology not abstract, make its Adder public and build the object outside of the class, but I don't know which pattern could be used for that ? I know the builder pattern and the factory pattern but I am not sure this is the right place for that. Any idea ?

Upvotes: 0

Views: 1417

Answers (1)

TomaszGuzialek
TomaszGuzialek

Reputation: 871

If you want to build an object with many parameters, the first thing I would think of is the Builder pattern.

Upvotes: 1

Related Questions