Skip to content

Commit

Permalink
refactored code to prevent circular dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
yuans-dev committed Jul 25, 2024
1 parent cbe4473 commit c2ad8c3
Show file tree
Hide file tree
Showing 12 changed files with 437 additions and 327 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/nbproject/private/
/build/
/dist/
1 change: 1 addition & 0 deletions cars.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ D07A###Honda###Civic###New###4000.0
8761###Toyota###Vios###New###4000.0
7555###Toyota###Vios###New###10000.0
CF79###Toyota###Prius###Blue###3400.0
4C32###Toyota###Fortuner###New###3700.0
57 changes: 30 additions & 27 deletions src/crms/form/MainForm.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,19 @@
*/
package crms.form;

import crms.lib.CarDatabase;
import crms.lib.CarFactory;
import crms.lib.CarInventory;
import crms.lib.RentalService;
import crms.lib.CarManager;
import crms.lib.CarReport;
import crms.lib.Rental;
import crms.lib.RentalDatabase;
import crms.lib.RentalManager;
import crms.lib.RentalReport;
import crms.lib.RentalReport.RentalStatus;
import crms.lib.gui.RentDateVerifier;
import crms.lib.gui.RentalTableModel;
import crms.lib.gui.CarTableModel;
import crms.lib.gui.IReportTableModel;
import crms.lib.gui.RentDateVerifier;
import crms.lib.gui.RentalTableModel;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
Expand All @@ -29,8 +32,8 @@
*/
public class MainForm extends javax.swing.JFrame {

private CarInventory carInventory;
private RentalService rentalService;
private CarManager carManager;
private RentalManager rentalManager;

/**
* Creates new form MainForm
Expand All @@ -39,12 +42,12 @@ public MainForm() {

initComponents();
modifyComponents();
initializeDatabase();
initializeProgram();

//save to disk before shutdown
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
carInventory.saveToDisk();
rentalService.saveToDisk();
rentalManager.getDatabase().saveToDisk();
carManager.getDatabase().saveToDisk();
}));
}

Expand Down Expand Up @@ -908,11 +911,11 @@ private void rentCarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN
JOptionPane.showMessageDialog(this, "Minimum rental period is 1 day");
return;
}
var success = rentalService.tryRentCar(carInventory.getCarById(idTextField_rent.getText().trim()), startDate, endDate);
var success = rentalManager.tryRentCar(carManager.getDatabase().getItemById(idTextField_rent.getText().trim()), startDate, endDate);
if (!success) {
JOptionPane.showMessageDialog(this, "Unit is not available");
} else {
updateCarTable(carInventory.generateReport(rentalService));
updateCarTable(carManager.generateReport());
}

}//GEN-LAST:event_rentCarButtonActionPerformed
Expand All @@ -924,14 +927,14 @@ private void registerCarButtonActionPerformed(java.awt.event.ActionEvent evt) {/
return;
}
try {
var carFactory = new CarFactory(carInventory);
var carFactory = new CarFactory(carManager.getDatabase());
var car = carFactory.createCar(brandTextField_add.getText(),
modelTextField_add.getText(),
descriptionTextField_add.getText(),
Double.parseDouble(priceTextField_add.getText())
);
carInventory.tryAddCar(car);
updateCarTable(carInventory.generateReport(rentalService));
carManager.tryAddCar(car);
updateCarTable(carManager.generateReport());
} catch (Exception e) {
}
}//GEN-LAST:event_registerCarButtonActionPerformed
Expand All @@ -943,9 +946,9 @@ private void removeCarButtonActionPerformed(java.awt.event.ActionEvent evt) {//G
return;
}
try {
var car = carInventory.getCarById(idTextField_remove.getText());
carInventory.tryRemoveCar(car);
updateCarTable(carInventory.generateReport(rentalService));
var car = carManager.getDatabase().getItemById(idTextField_remove.getText());
carManager.tryRemoveCar(car);
updateCarTable(carManager.generateReport());
} catch (Exception e) {
}
}//GEN-LAST:event_removeCarButtonActionPerformed
Expand All @@ -964,7 +967,7 @@ private void generateUnitsReportButtonActionPerformed(java.awt.event.ActionEvent
double priceMin = priceMinText.isBlank() ? Double.NEGATIVE_INFINITY : Double.parseDouble(priceMinText);
double priceMax = priceMaxText.isBlank() ? Double.POSITIVE_INFINITY : Double.parseDouble(priceMaxText);

var filterResult = carInventory.generateReport(rentalService)
var filterResult = carManager.generateReport()
.stream()
.filter(report -> (brand.isBlank() || report.getCar().getBrand().toLowerCase().contains(brand)))
.filter(report -> (model.isBlank() || report.getCar().getModel().toLowerCase().contains(model)))
Expand All @@ -979,7 +982,7 @@ private void generateUnitsReportButtonActionPerformed(java.awt.event.ActionEvent
private void generateRentalsReportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generateRentalsReportButtonActionPerformed
var active = rentActiveCheckBox_report.isSelected();
var inactive = rentInactiveCheckBox_report.isSelected();
var filterResult = rentalService.generateReport().stream()
var filterResult = rentalManager.generateReport().stream()
.filter(report -> (active ? report.getStatus() == RentalStatus.Active : true))
.filter(report -> (inactive ? report.getStatus() == RentalStatus.Inactive : true))
.collect(Collectors.toCollection(ArrayList::new));
Expand All @@ -994,9 +997,9 @@ private void cancelRentButtonActionPerformed(java.awt.event.ActionEvent evt) {//
}

try {
var rental = rentalService.getRentalById(rentalIdTextField_rent.getText());
rentalService.tryRemoveRental(rental);
updateRentalTable(rentalService.generateReport());
Rental rental = rentalManager.getDatabase().getItemById(rentalIdTextField_rent.getText());
rentalManager.tryRemoveRental(rental);
updateRentalTable(rentalManager.generateReport());
} catch (Exception e) {
}
}//GEN-LAST:event_cancelRentButtonActionPerformed
Expand Down Expand Up @@ -1065,7 +1068,7 @@ public void warn() {
}
var value = idTextField_rent.getText().trim();
new Thread(() -> {
var car = carInventory.getCarById(value);
var car = CarDatabase.getInstance().getItemById(value);
brandLabel_rent.setText(car.getBrand());
modelLabel_rent.setText(car.getModel());
descriptionLabel_rent.setText(car.getDescription());
Expand Down Expand Up @@ -1101,10 +1104,10 @@ public void warn() {

}

private void initializeDatabase() {
carInventory = CarInventory.getInstance();
rentalService = RentalService.getInstance(carInventory);
updateCarTable(carInventory.generateReport(rentalService));
private void initializeProgram() {
carManager = new CarManager(CarDatabase.getInstance());
rentalManager = new RentalManager(RentalDatabase.getInstance(CarDatabase.getInstance()));
updateCarTable(carManager.generateReport());
}

private void updateCarTable(ArrayList<CarReport> reportList) {
Expand Down
70 changes: 10 additions & 60 deletions src/crms/lib/CarInventory.java → src/crms/lib/CarDatabase.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,17 @@
* @author Yuan Suarez
* @version 1.0
*/
public class CarInventory {
public class CarDatabase extends Database<Car> {

private final String filename = "cars.txt";
private static CarInventory instance;
private final ArrayList<Car> cars;
private static CarDatabase instance;

/**
* Private constructor to prevent instantiation. Initializes the
* <code>cars</code> list.
*/
private CarInventory() {
cars = new ArrayList<>();
private CarDatabase() {
dataList = new ArrayList<>();
}

/**
Expand All @@ -46,79 +45,30 @@ private CarInventory() {
*
* @return the singleton instance of {@code CarInventory}.
*/
public static CarInventory getInstance() {
public static CarDatabase getInstance() {
if (instance == null) {
instance = new CarInventory();
instance = new CarDatabase();
instance.fetchFromDisk();
}
return instance;
}

/**
* Adds a {@code Car} to the inventory if its ID is unique.
*
* @param car The {@code Car} object to be added.
* @return True if the car was added successfully, false otherwise.
*/
public boolean tryAddCar(Car car) {
for (Car c : cars) {
if (c.getId() == null ? car.getId() == null : c.getId().equals(car.getId())) {
return false;
}
}
cars.add(car);
return true;
}

/**
* Removes a {@code Car} from the inventory based on its unique ID.
*
* @param car The {@code Car} object to be removed
* @return true if the car was removed successfully, false otherwise.
*/
public boolean tryRemoveCar(Car car) {
for (Car c : cars) {
if (c.getId() == null ? car.getId() == null : c.getId().equals(car.getId())) {
cars.remove(c);
return true;
}
}
return false;
}

/**
* Retrieves a {@code Car} object using the given ID.
*
* @param id the ID of the car to be retrieved
* @return the {@code Car} object with the specified ID, or null if not
* found
*/
public Car getCarById(String id) {
for (Car car : cars) {
public Car getItemById(String id) {
for (Car car : dataList) {
if (car.getId() == null ? id == null : car.getId().equals(id)) {
return car;
}
}
return null;
}

/**
* Generates a report that shows the properties and availability of each
* {@code Car} object.
*
* @param rentalService The {@code RentalService} instance required to check
* the availability of each {@code Car} object.
* @return an {@code ArrayList} of {@code CarReport} objects.
*/
public ArrayList<CarReport> generateReport(RentalService rentalService) {
var reports = new ArrayList<CarReport>();
for (Car car : cars) {
var report = new CarReport(car, rentalService.isCarAvailableNow(car));
reports.add(report);
}
return reports;
}

/**
* Fetches the recorded {@code Car} objects from the file {@code cars.txt}.
*
Expand All @@ -128,7 +78,7 @@ public void fetchFromDisk() {
while (reader.ready()) {
String text = reader.readLine();
String[] lineComponents = text.split("###");
cars.add(
dataList.add(
new Car(
lineComponents[0],//id
lineComponents[1],//brand
Expand All @@ -148,7 +98,7 @@ public void fetchFromDisk() {
public void saveToDisk() {
try (FileWriter fileWriter = new FileWriter(filename)) {
StringBuilder toWrite = new StringBuilder();
for (Car car : cars) {
for (Car car : dataList) {
toWrite.append(car.getId()).append("###")
.append(car.getBrand()).append("###")
.append(car.getModel()).append("###")
Expand Down
8 changes: 4 additions & 4 deletions src/crms/lib/CarFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,16 @@
*/
public class CarFactory {

private final CarInventory carInventory;
private final Database<Car> carDatabase;

/**
* Constructs a {@code CarFactory} object.
*
* @param carInventory The {@code CarInventory} instance required for some
* methods.
*/
public CarFactory(CarInventory carInventory) {
this.carInventory = carInventory;
public CarFactory(Database<Car> carDatabase) {
this.carDatabase = carDatabase;
}

/**
Expand All @@ -43,7 +43,7 @@ public Car createCar(String brand, String model, String description, double pric
String id;
do {
id = generateRandomId();
} while (carInventory.getCarById(id) != null);//Regenerate if it returns a car object
} while (carDatabase.getItemById(id) != null);//Regenerate if it returns a car object
return new Car(id, brand, model, description, price);
}

Expand Down
Loading

0 comments on commit c2ad8c3

Please sign in to comment.