-1

There are three Tables named as car_details, bike_details, truck_details the fields are same for all the three tables (RegistrationNo, No.ofYearsOld, OwnerName, ContactNo, VehicleType) the field VehicleType should specify type of the vehicle(car or bike or truck) and its default value is car.

All three tables have their separate POJO and repository

The task is I need to save the data into the corresponding table by considering the vehicleType field.

In My controller

@RequestMapping (value = "/createVehicle/", method = RequestMethod.POST, consumes = "application/json")
 @ResponseBody
 public ResponseEntity<> createGeneralAuthentication (@RequestBody CarDetails carDetails) {


        public void roleSelector(String type) {

            switch (type){
                case "car":
                    return new CarRepository();
                break;
                case "bike":
                    return new BikeRepository();
                break;
                case "truk":
                    return new TruckRepository();
                break;
            }
        }
   RolesRepository rolesRepository = new roleSelector(carDetails.getType());

        try {
            rolesRepository.save(carDetails);
        } catch (Exception ex) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);

        }
            return new ResponseEntity<>(HttpStatus.OK);
    }

No if else should be used it need to be a strategy pattern.

1 Answers1

0

Actually it's already a strategy pattern: each implementation behave differently and you're using a single interface to abstract their implementation details. Here roleSelector method is using for creating instances (like a factory).

Slava Semushin
  • 14,904
  • 7
  • 53
  • 69
  • but actually this code is not working, all I need is to make this pattern executable – Bavithran Mahendran Mar 08 '17 at 05:03
  • How it doesn't work? What error/exception it gives you? Why you didn't mention it in the question? My guess is that you have NullPointerException because of using `new` instead of injecting and using beans from Spring. – Slava Semushin Mar 08 '17 at 08:35
  • Actually, there are multiple errors.The object which I am passing is carDetails then by considering the type we have to choose the corresponding repository. Also we need to change the object type to match the repository. how can we do that. I tried to make interface the repositories but I can't able to make it. – Bavithran Mahendran Mar 14 '17 at 04:55