Is it a good idea to return a Builder from a Factory?

  softwareengineering

I would want to have a builder for creating a complex object, for example Employee.

I would want to be able to create my objects in two ways:

Case 1. Get Employee with default values

Case 2. Get Employee with default values, but then be able to change certain fields only

So, I am thinking of mixing Factory and Builder.

Something like that:

Case 1:

//Get a fully configured Employee with default values

Employee employee = EmployeeFactory.getDefault()

Case 2:

//Get a fully configured builder with default values, but change only the salary
//before finally building the Employee

Employee employee = EmployeeFactory.getDefaultBuilder().setSalary(5000).build();

Basically my Factory will either return an already built Employee or an EmployeeBuilder so I can further change only couple of fields per need.

Per my understanding of the Factory pattern by the book, it seems that Factory concept is broken as it returns both an object and a builder.

Is there anything wrong with this approach per your opinion?

LEAVE A COMMENT