I have an app where the user can add to a repository cars, trucks, and bikes. All of these entity types implement a 'Vehicle' interface (I am using Java, but this could be in any OOP language to be honest). I am using the model-view-controller design pattern where the user gives the vehicle characteristics in the view, these are passed to the controller which validates the characteristics and builds a vehicle, and then this vehicle is sent to the repository where it is added. All of these 3 vehicles (car, truck, bike) have the same attributes and look somewhat like this (I'll give the example of 'Car' and I'll also show the 'Vehicle' interface):
public interface Vehicle{
int getId();
double getRepairCost();
String getColor();
int getWeight();
int getVehiclePrice();
}
public class Car implements Vehicle{
private int id;
private int weight;
private int vehiclePrice;
private String color;
public Car(int id, int weight, int vehiclePrice, String color) {
this.id = id;
this.weight = weight;
this.color = color;
this.vehiclePrice = vehiclePrice;
}
}
The other 2 vehicles are similar in attributes and constructor. I know I can use an abstract class, but I decided to go with the interface.
My question is this: After I know what type of vehicle the user wants to create what is the recommended way to create this vehicle and add it to the repository? Currently what I have in the controller is something like this:
public void controllerAddCar(int id, int weight, int vehiclePrice, String color) throws AddItemException {
Car newCar = new Car(id, weight, vehiclePrice, color);
this.repo.repoAddVehicle(newCar); // this method inside repo throws an exception if a vehicle with the given ID already exists, but it's not important to this question
}
public void controllerAddTruck(int id, int weight, int vehiclePrice, String color) throws AddItemException {
Truck newTruck = new Truck(id, weight, vehiclePrice, color);
this.repo.repoAddVehicle(newTruck);
}
public void controllerAddBike(int id, int weight, int vehiclePrice, String color) throws AddItemException {
Bike newBike = new Bike(id, weight, vehiclePrice, color);
this.repo.repoAddVehicle(newBike);
}
So after the user decides what type of vehicle he wants to create I use the corresponding function. This, however, looks like it could get very messy very quickly. What if I manage an online store with thousands of entities? Will I create thousands of functions like I did above? What is the better alternative? I'm just getting started with these things so I don't really see if what I did is an acceptable way to solve this issue and what is the better alternative.
Aucun commentaire:
Enregistrer un commentaire