I'm currently designing the domain for a reservation system meant for 2 types of reservations.
Both of these types have common properties, such as their date and location. Both also have properties which the other does not, though. Examples here are in one type you can bring along guests, and not with the other; or you can request lunch for one type, and not the other.
Currently I have an abstract Reservation class, with a concrete implementations per type of reservation. I then have a ReservationBuilder which takes an enum (reservation type) as argument in its constructor. This builder would then contain methods for both types of reservations, and using a method for a type of reservation that cannot use the information would either do nothing when built, or throw an error.
Something tells me that this isn't a good use of this pattern, though. Would it be better to abstract the builder too? Or would a factory pattern better suit my use case?
CodePudding user response:
You have identified the need for an abstract superclass, Reservation
. You have also identified the need for specialization in child classes, like GroupReservation
, RoomServiceReservation
.
What is the motivation for using a builder or factory pattern? If the problem is to create a new instance of a class given a string, a few if
statements or a case
statement would work fine.
if(userSelection.equals("group")) {
return new GroupReservation();
}
If the motivation is for something more complex, a builder or factory class might be useful. The messy details of selecting and instantiating a concrete class can be hidden that way.
Object-oriented programmers can unwittingly wear "pattern goggles". When we wear pattern goggles, we approach every design choice looking for just the right pattern to implement. Sometimes there is a language feature we can use that eliminates the need for a pattern. And sometimes an if
statement is good enough.