Skip to content

Instantly share code, notes, and snippets.

@boris317
Last active March 26, 2019 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boris317/ac600b2bc3e22afab8e5e61f660b2955 to your computer and use it in GitHub Desktop.
Save boris317/ac600b2bc3e22afab8e5e61f660b2955 to your computer and use it in GitHub Desktop.
class AirBookingService {
private final Database db;
private final BookingService bookings;
private static final Map<String, User> userCache = new HashMap<>();
public AirBookingService() {
db = new Database();
bookings = BookingServiceFactory.getService();
}
public Trip bookTicket(long productId, PaymentContext context) {
final FlightProduct product = getFlightProduct(productId);
final User user = getUser(context.getUserId());
final UnbookedTrip unbookedTrip = createTrip(product, user);
final Trip trip = bookings.bookTrip(unbookedTrip);
addRewardPointsToUser(trip, user);
return trip;
}
private User getUser(long id) {
final Connection conn = db.getConnection();
if (userCache.containsKey(id)) {
return userCache.get(id);
}
try {
final User user = conn.query("select * from users where id = " + id, new UserMapper());
user.put(id, user);
return user;
} finally {
conn.close();
}
}
private FlightProduct getFlightProduct(long id) {
final Connection conn = db.getConnection();
try {
return conn.query("select * from products where id = " + id, new FlightProductMapper());
} finally {
conn.close();
}
}
private void addRewardPointsToUser(Trip trip, User user) {
final Connection conn = db.getConnection();
try {
conn.query("update users set totalRewardsPoints = totalRewardsPoints + " + trip.getPoints() + " where id = " + user.getId());
} finally {
conn.close();
}
}
private UnbookedTrip createTrip(FlightProduct product, User user) {
// Creates and returns and UnbookedTrip.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment