Reputation: 935
I'm trying to clean up some code I have written for reading data. I have two sources of data: a database and a file. Both currently have separate classes and both classes have optional, non common, parameters in the constructors provided (at the moment traditional telescoping constructors).Both classes Implement interface MyData and when I instantiate the objects I always instantiate a MyData object.
I want to merge these classes into a single class and make the instantiation as clean as possible but I can't figure out how. Im certain its a mixture of builder and factory patterns.The user should never have to see the underlying type MyDatabaseData and MyFileData, just MyData. Can someone help me by sketching out a similar example just to set me off in the right direction
Upvotes: 0
Views: 335
Reputation: 109547
A builder pattern would look like this:
MyDatabaseData data = MyDatabaseData.create()
.authenticate("admin", "rumpelstielchen")
.get();
public class MyDatabaseData {
private MyDatabaseData() { }
public static MyDatabaseBuilder create() {
return new MyDatabaseBuilder(new MyDatabaseData());
}
}
public class MyDatabaseBuilder {
private MyDatabaseData data;
MyDatabaseBuilder(MyDatabaseData data) {
this.data = data;
}
public MyDatabaseData get() {
return data; // Do checks and yield the final result
}
public MyDatabaseBuilder authenticate(String user, String password) {
...
return this; // For chaining calls
}
}
Whether to use common base classes/interfaces is a matter of suitability:
public class MyDatabaseBuilder extends MyBuilder<MyDatabaseData>
However you will probably need to do specific things and hence need child classes. Development not necessarily will become easier, maintaining 4 classes with parallel evolutions.
Upvotes: 0
Reputation: 31648
Keep the classes separate since they do different things. Combining them will only make a giant mess and violates the Single Responsibility Principle.
If you don't want the users to see the classes, then make the classes package private.
Then you make a new Builder or Factory class that takes parameters and figures out which class to instantiate.
Hope this helps.
Upvotes: 1