问题描述:

I have a class with (say) 50 fields. I only use a few of them per deployment of the program per user need. Is there a way to make the constructor generic yet specific to the deployment?

e.g

public class Employee{

private String id = "default";

private String empcat = "default";

private String empfam = "default";

private String phychar = "default";

private String othchar = "default";

private String shoesty = "default";

private Double shoesiz = 0.0;

private String shoesty = "default";

private Double shirsiz = 0.0;

private String shirsty = "default";

.........50 other fields..

}

"User/Customer 1" - only wants to use the program for shoe and thus instantiates the object with :

Employee obemp = new Employee("John", 11.5, Dockers); (i.e. id, shoesiz and shoesty)

User/Customer 2 - only wants to use the program for shirt and thus instantiates the object with :

Employee obemp = new Employee("John", 42, ABC); (i.e. id, shirsiz and shirsty)

User/Customer 3 - only wants to use the program for family and thus instantiates the object with :

Employee obemp = new Employee("John", "Smith"); (i.e. id, empfam)

The order of the fields during the object creation can be different - depending on the usage in the model.

网友答案:

First of all, I'd suggest breaking your main class down into smaller pieces that manage data which typically goes together (Shoe information, Shirt information, Family information, etc.).

Secondly, I'd suggest you provide customers with a builder pattern to make it easy for them to construct an object with just the pieces that they're likely to need. That way, they can do something like this:

Employee emp = new EmployeeBuilder("John")
    .withShirtInfo(shirsiz, shirsty)
    .build();
网友答案:

There is no generic way in core java to do this. But you may use some design pattern like - builder pattern.

You may also create an Employee with some minimum criteria like - id. We can assume each Employee have an id. So create an Employee with the id using the Employee(String id) constructor -

public class Employee{

     //all properties

   public Employee(String id){
      this.id = id;
   }

   //setter methods
}  

Suppose you have create an Employee like this -

Employee employee = new Employee("eng134");   

After that you can set only required property to employee object using the setter methods -

employee.setShoesiz(9);
employee.setShirsiz(26);
相关阅读:
Top