0% found this document useful (0 votes)
11 views

Final j Component

The document outlines a project proposal for developing a banking system using design patterns to address inefficiencies in transaction processing and account management. It emphasizes the use of the Facade, Strategy, and Chain of Responsibility patterns to create a modular, scalable, and user-friendly application that can adapt to changing business needs. The project aims to enhance the overall user experience while ensuring accurate and timely processing of banking operations.

Uploaded by

naresh.r2021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Final j Component

The document outlines a project proposal for developing a banking system using design patterns to address inefficiencies in transaction processing and account management. It emphasizes the use of the Facade, Strategy, and Chain of Responsibility patterns to create a modular, scalable, and user-friendly application that can adapt to changing business needs. The project aims to enhance the overall user experience while ensuring accurate and timely processing of banking operations.

Uploaded by

naresh.r2021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

School of Computer Science Engineering and

Information Systems (SCORE)

Fall Semester 2024-25


SWE2019 – DESIGN PATTERN

REVIEW

PROJECT TITLE : BANKING SYSTEM


SLOT : A2
FACULTY NAME : USHA PREETHI P

TEAM MEMBERS:
KISHORE.S - 21MIS0280
KAUSHIK.K – 21MIS0332
NARESH.R – 21MIS0354
1.Problem Statement:
• Banking customers frequently encounter delays and errors in transaction
processing and account management due to outdated and manual banking
procedures.
• The government is concerned about the inefficiencies in the current
system and seeks to develop a software solution that can automate and
streamline banking operations. The new system should simplify complex
financial services, ensure accurate and timely processing of transactions,
and provide a consistent user experience, reducing the risk of human
errors and operational bottlenecks.

2.Motivation for Choosing the Work:


In a banking system, handling complex and varied operations like account
management, transaction processing, and loan approvals requires a flexible and
scalable architecture. Design patterns offer proven solutions to common
software design challenges, making them an ideal choice for building a robust
banking application.
• Facade Pattern simplifies client interactions by providing a unified
interface to the complex subsystems within the bank, such as account
management, loan processing, and transaction history. This makes the
system more user-friendly and easier to maintain.
• Strategy Pattern enables the banking application to dynamically choose
different interest calculation methods or transaction validation rules based
on account types or regulatory requirements. This flexibility is essential
for adapting to changing business needs and customer preferences.
• Chain of Responsibility Pattern allows the system to process loan
approvals or other multi-step operations by passing requests through a
chain of handlers (e.g., credit check, manager approval, legal review).
This ensures that each request is handled appropriately, without
overwhelming a single component of the system.
These design patterns not only improve the modularity and reusability of the
code but also ensure that the system can evolve with changing requirements,
enhancing both maintainability and scalability.
3.Domain of the Project:
• The domain of this project lies within the financial services industry,
specifically focusing on the development of a modular and scalable
banking system. The system is designed to manage various banking
operations, including account management, transaction processing, loan
approvals, and customer interactions. By leveraging software design
patterns such as the Facade Pattern, Strategy Pattern, and Chain of
Responsibility Pattern, the project aims to address the complexities and
challenges associated with maintaining flexibility, efficiency, and
reliability in banking software.
• The system must accommodate a variety of banking functions while
ensuring that it remains adaptable to changing business requirements,
regulatory environments, and customer needs. Through the strategic use
of design patterns, the project seeks to create a robust architecture that
supports seamless integration of new features, minimizes the risk of
errors, and enhances the overall user experience for both customers and
bank employees.

4.Design Patterns Involvement:


1. Facade Pattern:

• Purpose: Simplifies interactions with complex subsystems by providing


a unified interface.
• Involvement:
o A BankingFacade class will be implemented to provide a
simplified interface to clients for accessing core banking operations
like account management, loan processing, and transaction history.
o This pattern hides the complexities of various subsystems and
allows users to perform operations without needing to understand
the underlying implementation.
2. Strategy Pattern:
• Purpose: Allows the selection of different algorithms or strategies at
runtime.

• Involvement:
o An InterestCalculationContext class will use different interest
calculation strategies (e.g., fixed-rate, variable-rate) depending on
the account type (savings, fixed deposit, etc.).
o This pattern enables the bank to modify interest calculation
methods without altering the underlying structure, ensuring
adaptability to new financial products or regulatory changes
.
3. Chain of Responsibility Pattern:
• Purpose: Processes requests through a chain of handlers, where each
handler decides whether to process the request or pass it to the next
handler

• Involvement:
o A LoanApprovalChain will be implemented where a loan request
is passed through various stages (e.g., credit check, managerial
approval, legal review) before a final decision is made.
This pattern allows for flexible and manageable processing of multi-
step operations, ensuring that each request is handled according to
specific criteria.
5. Details of design pattern with respect to the scenario (Intent,
Structure) :
1. Facade Pattern
Intent:
The Facade Pattern provides a unified interface to a set of interfaces
in a subsystem. It simplifies the interaction between the client and the
complex subsystems involved in the banking operations. By using the
Facade, the client doesn’t need to deal with the intricacies of how
various banking services (like account management, loan processing,
and transaction history) work. It provides a simplified interface that
shields the client from the underlying complexity.
In our scenario, the Facade pattern is used to handle complex
banking operations such as opening an account, processing a loan,
and viewing transaction history in a unified manner.
Structure:
• Client: The Main class where user inputs are processed.
• Facade: The BankingFacade class that simplifies the banking
operations.
• Subsystems: The actual classes that perform the operations:
o AccountService: Manages the process of opening an
account.
o LoanService: Manages the process of processing loans.
o TransactionService: Manages the retrieval and viewing
of transaction history.
2. Strategy Pattern
Intent:
The Strategy Pattern defines a family of algorithms (strategies),
encapsulates each one, and makes them interchangeable. The strategy
pattern allows algorithms to vary independently from the clients that
use them. This pattern is useful when there are multiple ways to
perform a certain task, and the best algorithm can be selected at
runtime.
In our banking scenario, the Strategy Pattern is used to calculate
interest in two different ways:
• FixedRateInterestStrategy: A fixed interest rate is applied.
• VariableRateInterestStrategy: A variable interest rate is
applied, depending on user input.
Structure:
• Context: The InterestCalculationContext class, which maintains
a reference to the current interest calculation strategy.
• Strategy Interface: InterestCalculationStrategy interface that
defines the method for calculating interest.
• Concrete Strategies: Classes that implement different interest
calculation methods:
o FixedRateInterestStrategy: A strategy for calculating fixed
rate interest.
o VariableRateInterestStrategy: A strategy for calculating
variable rate interest.
3. Chain of Responsibility Pattern
Intent:
The Chain of Responsibility Pattern is used to allow more than one
handler (object) to process a request. The request is passed along a
chain of handlers, and each handler either processes the request or
passes it to the next handler in the chain.
In the banking system, the Chain of Responsibility is used in the
loan approval process. A loan request must go through a series of
checks (credit check, manager approval, legal review), and each
handler in the chain either approves or rejects the loan or forwards it
to the next handler.
Structure:
• Handler Interface: LoanApprovalHandler, the base interface
for all handlers in the chain.
• Concrete Handlers: Specific handlers that process parts of the
loan approval process:
o CreditCheckHandler: Handles the credit score validation.
o ManagerApprovalHandler: Handles approval from the
manager.
o LegalReviewHandler: Handles the legal review of the
loan.
• Request: LoanRequest, encapsulates the loan details (amount,
credit score, etc.).
6. Code for each component:
1. Façade pattern:
Main class:
import java.util.Scanner;

public class Main {

private static String accountType = null;

private static String loanType = null;

private static double loanAmount = 0;

private static int creditScore = 0;

private static double interest = 0;

private static boolean loanApproved = false;

public static void main(String[] args) {

BankingFacade bankingFacade = new BankingFacade();

InterestCalculationContext interestContext = new InterestCalculationContext();

Scanner scanner = new Scanner(System.in);

boolean exit = false;

while (!exit) {

System.out.println("====== Banking System Menu ======");

System.out.println("1. Open an Account");

System.out.println("2. Process a Loan");

System.out.println("3. View Transaction History");

System.out.println("4. Calculate Interest");

System.out.println("5. Loan Approval Process");

System.out.println("6. Exit");

System.out.print("Enter your choice: ");


int choice = scanner.nextInt();

scanner.nextLine(); // Consume newline

switch (choice) {

case 1:

openAccount(bankingFacade, scanner);

break;

case 2:

processLoan(bankingFacade, scanner);

break;

case 3:

bankingFacade.viewTransactionHistory();

break;

case 4:

calculateInterest(interestContext, scanner);

break;

case 5:

loanApprovalProcess(scanner);

break;

case 6:

exit = true;

printReceipt();
System.out.println("Exiting the Banking System. Goodbye!");

break;

default:

System.out.println("Invalid choice! Please try again.");

System.out.println();

scanner.close();

// Method to open an account

private static void openAccount(BankingFacade bankingFacade, Scanner scanner) {

System.out.print("Enter account type (Savings/Checking): ");

accountType = scanner.nextLine();

bankingFacade.openAccount(accountType);

// Method to process a loan

private static void processLoan(BankingFacade bankingFacade, Scanner scanner) {

System.out.print("Enter loan type (Home/Car/Personal): ");

loanType = scanner.nextLine();

bankingFacade.processLoan(loanType);

// Method to calculate interest using Strategy pattern

private static void calculateInterest(InterestCalculationContext interestContext, Scanner scanner) {


System.out.println("Choose Interest Type:");

System.out.println("1. Fixed Rate");

System.out.println("2. Variable Rate");

int interestChoice = scanner.nextInt();

System.out.print("Enter loan amount: ");

loanAmount = scanner.nextDouble();

if (interestChoice == 1) {

interestContext.setStrategy(new FixedRateInterestStrategy());

} else if (interestChoice == 2) {

System.out.print("Enter variable rate (e.g., 0.07 for 7%): ");

double variableRate = scanner.nextDouble();

interestContext.setStrategy(new VariableRateInterestStrategy(variableRate));

} else {

System.out.println("Invalid choice! Returning to main menu.");

return;

interest = interestContext.calculateInterest(loanAmount);

System.out.println("Calculated Interest: " + interest);

// Method to handle the loan approval process using Chain of Responsibility pattern

private static void loanApprovalProcess(Scanner scanner) {

System.out.print("Enter loan amount: ");

loanAmount = scanner.nextDouble();

System.out.print("Enter your credit score: ");

creditScore = scanner.nextInt();
LoanRequest loanRequest = new LoanRequest(loanAmount, creditScore);

LoanApprovalHandler creditCheck = new CreditCheckHandler();

LoanApprovalHandler managerApproval = new ManagerApprovalHandler();

LoanApprovalHandler legalReview = new LegalReviewHandler();

creditCheck.setNextHandler(managerApproval);

managerApproval.setNextHandler(legalReview);

creditCheck.processRequest(loanRequest);

// If credit score is acceptable, assume loan is approved

loanApproved = creditScore > 600;

// Method to print the receipt before exiting

private static void printReceipt() {

System.out.println("====== Receipt Summary ======");

if (accountType != null) {

System.out.println("Account Type: " + accountType);

} else {

System.out.println("No account opened.");

if (loanType != null) {

System.out.println("Loan Type: " + loanType);

System.out.println("Loan Amount: $" + loanAmount);


System.out.println("Interest: $" + interest);

System.out.println("Loan Approval: " + (loanApproved ? "Approved" : "Rejected"));

} else {

System.out.println("No loan processed.");

System.out.println("=============================");

BankingFacade class:
class BankingFacade {

private AccountService accountService;

private LoanService loanService;

private TransactionService transactionService;

public BankingFacade() {

accountService = new AccountService();

loanService = new LoanService();

transactionService = new TransactionService();

public void openAccount(String accountType) {

accountService.openAccount(accountType);

public void processLoan(String loanType) {

loanService.processLoan(loanType);

public void viewTransactionHistory() {

transactionService.viewTransactionHistory();

}
2. Strategy pattern:
InterestCalculationContext class:
class InterestCalculationContext {

private InterestCalculationStrategy strategy;

public void setStrategy(InterestCalculationStrategy strategy) {

this.strategy = strategy;

public double calculateInterest(double amount) {

return strategy.calculateInterest(amount);

InterestCalculationStrategy class:
interface InterestCalculationStrategy {

double calculateInterest(double amount);

FixedRateInterestStrategy class:
class FixedRateInterestStrategy implements InterestCalculationStrategy {

private static final double FIXED_RATE = 0.05;

@Override

public double calculateInterest(double amount) {

return amount * FIXED_RATE;

}
3. Chain Of Responsibility pattern:
LoanApprovalHandler class:
abstract class LoanApprovalHandler {

protected LoanApprovalHandler nextHandler;

public void setNextHandler(LoanApprovalHandler nextHandler) {

this.nextHandler = nextHandler;

public void processRequest(LoanRequest request) {

if (nextHandler != null) {

nextHandler.processRequest(request);

CreditCheckHandler class:
class CreditCheckHandler extends LoanApprovalHandler {

@Override

public void processRequest(LoanRequest request) {

System.out.println("Performing credit check...");

if (request.getCreditScore() > 600) {

super.processRequest(request);

} else {

System.out.println("Loan rejected due to low credit score.");

ManagerApprovalHandler class:
class ManagerApprovalHandler extends LoanApprovalHandler {
@Override

public void processRequest(LoanRequest request) {

System.out.println("Manager approval in process...");

if (request.getAmount() <= 50000) {

System.out.println("Loan approved by manager.");

} else {

super.processRequest(request);

LegalReviewHandler class:
class LegalReviewHandler extends LoanApprovalHandler {

@Override

public void processRequest(LoanRequest request) {

System.out.println("Legal review in process...");

System.out.println("Loan approved after legal review.");

}
7. Collaboration of code (Flow):
1. Facade Pattern Collaboration Flow
Objective:
The Facade pattern simplifies interactions with various subsystems
(Account, Loan, Transaction) by providing a unified interface
(BankingFacade) for common banking operations like opening an
account, processing loans, viewing transaction history, etc.
Participants:
• Client: Main class
• Facade: BankingFacade class
• Subsystems:
o AccountService
o LoanService
o TransactionService
Flow of Collaboration:
1. Client Interaction (Main Class):
o The user chooses an operation from the menu (e.g.,
opening an account, processing a loan, etc.).
o The Main class doesn't directly interact with any
subsystem services. Instead, it interacts with the
BankingFacade, which provides a high-level, simplified
interface to the banking services.
2. Facade Interaction (BankingFacade):
o The Main class calls a method on the BankingFacade,
such as openAccount(), processLoan(), or
viewTransactionHistory().
o The BankingFacade then interacts with the corresponding
subsystem class (such as AccountService, LoanService,
TransactionService) to perform the actual operation.
3. Subsystems Interaction:
o Each subsystem class (AccountService, LoanService,
TransactionService) performs the required task and returns
the results back to the BankingFacade.
o The BankingFacade then forwards the results to the client
(Main class).
Example Flow:
1. Client (Main) calls BankingFacade.openAccount().
2. BankingFacade forwards the request to AccountService,
which handles the account creation.
3. The result is returned to BankingFacade, which forwards it to
the Client (Main).
Client (Main) → BankingFacade → Subsystem (AccountService,
LoanService, TransactionService)
2. Strategy Pattern Collaboration Flow
Objective:
The Strategy pattern enables the interest calculation mechanism to be
flexible by allowing different strategies (fixed or variable interest
rates) to be selected at runtime based on user input.
Participants:
• Context: InterestCalculationContext
• Strategy Interface: InterestCalculationStrategy
• Concrete Strategies:
o FixedRateInterestStrategy
o VariableRateInterestStrategy
Flow of Collaboration:
1. Client Interaction (Main Class):
o The user chooses the interest calculation option (fixed rate
or variable rate).
o The Main class instantiates the
InterestCalculationContext.
2. Setting the Strategy:
o The Main class selects the interest calculation strategy
based on user input and sets it in the
InterestCalculationContext using the setStrategy()
method.
o The strategy can be either FixedRateInterestStrategy or
VariableRateInterestStrategy.
3. Executing the Strategy:
o When the interest needs to be calculated, the
InterestCalculationContext calls the calculateInterest()
method, which delegates the interest calculation to the
current strategy (fixed or variable).
4. Result:
o The result of the interest calculation is returned to the
Main class, where it can be displayed to the user.
Example Flow:
1. Client (Main) calls setStrategy(new
FixedRateInterestStrategy()) on InterestCalculationContext.
2. The InterestCalculationContext stores the strategy.
3. When InterestCalculationContext.calculateInterest() is called, it
forwards the request to the set strategy
(FixedRateInterestStrategy), which performs the calculation.
4. The calculated interest is returned to the Main class.
Client (Main) → InterestCalculationContext →
InterestCalculationStrategy (FixedRate or VariableRate)
3. Chain of Responsibility Pattern Collaboration Flow
Objective:
The Chain of Responsibility pattern is used in the loan approval
process to ensure that the loan request passes through various
approval stages (credit check, manager approval, legal review) before
final approval or rejection.
Participants:
• Request: LoanRequest
• Handler Interface: LoanApprovalHandler
• Concrete Handlers:
o CreditCheckHandler
o ManagerApprovalHandler
o LegalReviewHandler
Flow of Collaboration:
1. Client Interaction (Main Class):
o The user selects the loan approval process.
o The Main class creates a LoanRequest and sends it to the
first handler in the chain (CreditCheckHandler).
2. Request Processing by Handlers:
o CreditCheckHandler processes the request first by
checking the credit score.
o If the credit check is passed, the request is forwarded to
the next handler, ManagerApprovalHandler.
o ManagerApprovalHandler performs managerial
approval and, if successful, forwards the request to the
next handler, LegalReviewHandler.
3. Final Approval or Rejection:
o After passing through all the handlers in the chain, the
final decision is made, and the result is returned to the
Main class.
4. Result:
o The Main class receives the loan approval or rejection
result and displays it to the user.
Example Flow:
1. Client (Main) creates a LoanRequest and passes it to the first
handler in the chain, CreditCheckHandler.
2. CreditCheckHandler processes the request and forwards it to
ManagerApprovalHandler if successful.
3. ManagerApprovalHandler processes the request and forwards
it to LegalReviewHandler if successful.
4. LegalReviewHandler makes the final decision and returns the
result to the client.
Client (Main) → LoanApprovalHandler (CreditCheckHandler)
→ LoanApprovalHandler (ManagerApprovalHandler) →
LoanApprovalHandler (LegalReviewHandler)
8. Sample Output Screenshots:
9. Modifications given by faculty:
We were asked to add additional functionalities and connect with
MySQL Database.
Design patterns (structure with respect to scenario):
1. Facade Pattern
The Facade Pattern provides a unified interface to a set of interfaces
in a subsystem. It simplifies the interaction between the client and the
complex subsystems involved in the banking operations. By using the
Facade, the client doesn’t need to deal with the intricacies of how
various banking services (like account management, loan processing,
and transaction history) work. It provides a simplified interface that
shields the client from the underlying complexity.
In our scenario, the Facade pattern is used to handle complex
banking operations such as opening an account, processing a loan,
and viewing transaction history in a unified manner.
Structure:
• Client: The Main class where user inputs are processed.
• Facade: The BankingFacade class that simplifies the banking
operations.
• Subsystems: The actual classes that perform the operations:
o AccountService: Manages the process of opening an
account.
o LoanService: Manages the process of processing loans.
o TransactionService: Manages the retrieval and viewing
of transaction history.
2. Strategy Pattern
The Strategy Pattern defines a family of algorithms (strategies),
encapsulates each one, and makes them interchangeable. The strategy
pattern allows algorithms to vary independently from the clients that
use them. This pattern is useful when there are multiple ways to
perform a certain task, and the best algorithm can be selected at
runtime.
In our banking scenario, the Strategy Pattern is used to calculate
interest in two different ways:
• FixedRateInterestStrategy: A fixed interest rate is applied.
• VariableRateInterestStrategy: A variable interest rate is
applied, depending on user input.
Structure:
• Context: The InterestCalculationContext class, which maintains
a reference to the current interest calculation strategy.
• Strategy Interface: InterestCalculationStrategy interface that
defines the method for calculating interest.
• Concrete Strategies: Classes that implement different interest
calculation methods:
o FixedRateInterestStrategy: A strategy for calculating fixed
rate interest.
o VariableRateInterestStrategy: A strategy for calculating
variable rate interest.
3. Chain of Responsibility Pattern
The Chain of Responsibility Pattern is used to allow more than one
handler (object) to process a request. The request is passed along a
chain of handlers, and each handler either processes the request or
passes it to the next handler in the chain.
In the banking system, the Chain of Responsibility is used in the
loan approval process. A loan request must go through a series of
checks (credit check, manager approval, legal review), and each
handler in the chain either approves or rejects the loan or forwards it
to the next handler.
Structure:
• Handler Interface: LoanApprovalHandler, the base interface
for all handlers in the chain.
• Concrete Handlers: Specific handlers that process parts of the
loan approval process:
o CreditCheckHandler: Handles the credit score validation.
o ManagerApprovalHandler: Handles approval from the
manager.
o LegalReviewHandler: Handles the legal review of the
loan.
• Request: LoanRequest, encapsulates the loan details (amount,
credit score, etc.).
CODE:
MySQL coding :
CREATE DATABASE LoanManagement;

USE LoanManagement;

CREATE TABLE accounts (


account_number INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
password VARCHAR(100),
dob DATE,
phone VARCHAR(15),
address VARCHAR(255),
account_type VARCHAR(10)
);

CREATE TABLE loans (


loan_id INT AUTO_INCREMENT PRIMARY KEY,
account_number INT,
loan_type VARCHAR(20),
loan_amount DOUBLE,
interest DOUBLE,
status VARCHAR(20),
FOREIGN KEY (account_number) REFERENCES
accounts(account_number)
);
Connecting Banking System with Databse(MySQL) :
import java.sql.*;
import java.util.Scanner;

// MySQL Connector
class MySQLConnector {
private static final String URL =
"jdbc:mysql://localhost:3306/LoanManagement";
private static final String USER = "root"; // Replace with your
MySQL username
private static final String PASSWORD = "NareshR31#"; // Replace
with your MySQL password

public static Connection getConnection() throws SQLException {


return DriverManager.getConnection(URL, USER,
PASSWORD);
}
}

Account Management Class:


class AccountManager {
public void createAccount() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Name: ");
String name = scanner.nextLine();
System.out.print("Enter Password: ");
String password = scanner.nextLine();
System.out.print("Enter DOB (YYYY-MM-DD): ");
String dob = scanner.nextLine();
System.out.print("Enter Phone Number: ");
String phone = scanner.nextLine();
System.out.print("Enter Address: ");
String address = scanner.nextLine();
System.out.println("Select Account Type: 1. Saving 2. Current");
int accountTypeChoice = scanner.nextInt();
String accountType = (accountTypeChoice == 1) ? "saving" :
"current";

String query = "INSERT INTO accounts (name, password, dob,


phone, address, account_type) VALUES (?, ?, ?, ?, ?, ?)";

try (Connection conn = MySQLConnector.getConnection();


PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, name);
pstmt.setString(2, password);
pstmt.setString(3, dob);
pstmt.setString(4, phone);
pstmt.setString(5, address);
pstmt.setString(6, accountType);
pstmt.executeUpdate();
System.out.println("Account created successfully!");
} catch (SQLException e) {
System.out.println("Error creating account: " +
e.getMessage());
}
}

public boolean login() {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter Username: ");
String username = scanner.nextLine();
System.out.print("Enter Password: ");
String password = scanner.nextLine();

String query = "SELECT account_number FROM accounts


WHERE name = ? AND password = ?";
try (Connection conn = MySQLConnector.getConnection();
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, username);
pstmt.setString(2, password);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
System.out.println("Login successful. Account Number: "
+ rs.getInt("account_number"));
return true;
} else {
System.out.println("Invalid username or password.");
}
}
} catch (SQLException e) {
System.out.println("Error during login: " + e.getMessage());
}
return false;
}
}

Loan Management Class:


class LoanManager {
public void applyForLoan(int accountNumber) {
Scanner scanner = new Scanner(System.in);

// Ask for the user's credit score


System.out.print("Enter your credit score: ");
int creditScore = scanner.nextInt();

// Check if credit score is less than 750


if (creditScore < 750) {
System.out.println("Your credit score is " + creditScore + ".
Loan application rejected.");
return;
}
// Proceed with loan application if credit score is sufficient
System.out.println("Select Loan Type: 1. Vehicle 2. Education 3.
Personal 4. Home");
int loanTypeChoice = scanner.nextInt();
String loanType = switch (loanTypeChoice) {
case 1 -> "vehicle";
case 2 -> "education";
case 3 -> "personal";
case 4 -> "home";
default -> throw new IllegalArgumentException("Invalid loan
type.");
};

System.out.print("Enter Loan Amount: ");


double loanAmount = scanner.nextDouble();

String query = "INSERT INTO loans (account_number,


loan_type, loan_amount, interest, status) VALUES (?, ?, ?, ?,
'pending')";
try (Connection conn = MySQLConnector.getConnection();
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setInt(1, accountNumber);
pstmt.setString(2, loanType);
pstmt.setDouble(3, loanAmount);
pstmt.setDouble(4, 0.0); // Initial interest is set to 0.0
pstmt.executeUpdate();
System.out.println("Loan request submitted successfully.");
} catch (SQLException e) {
System.out.println("Error applying for loan: " +
e.getMessage());
}
}

public void selectInterestRate() {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter Loan ID to update interest: ");
int loanId = scanner.nextInt();

//Fetch the loan details


String query = "SELECT loan_amount, interest FROM loans
WHERE loan_id = ?";
try (Connection conn = MySQLConnector.getConnection();
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setInt(1, loanId);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
double loanAmount = rs.getDouble("loan_amount");
double interestRate = 0;
System.out.println("Select Interest Rate Type:");
System.out.println("1. Fixed Rate");
System.out.println("2. Variable Rate");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();

switch (choice) {
case 1 -> interestRate = loanAmount * 0.05; // Fixed
rate is 5% (0.05)
case 2 -> {
System.out.print("Enter the Variable Interest Rate (in
percentage): ");
interestRate = loanAmount * (scanner.nextDouble() /
100); // Convert to decimal
}
default -> System.out.println("Invalid choice.");
}

// Update interest in the loan


updateLoanInterestRate(loanId, interestRate);
} else {
System.out.println("Loan ID not found.");
}
}
} catch (SQLException e) {
System.out.println("Error updating loan interest rate: " +
e.getMessage());
}
}

// Helper method to update interest rate in the loans table


private void updateLoanInterestRate(int loanId, double interestRate)
{
String query = "UPDATE loans SET interest = ? WHERE loan_id
= ?";
try (Connection conn = MySQLConnector.getConnection();
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setDouble(1, interestRate);
pstmt.setInt(2, loanId);
pstmt.executeUpdate();
System.out.println("Loan interest rate updated successfully.");
} catch (SQLException e) {
System.out.println("Error updating loan interest rate: " +
e.getMessage());
}
}

public void viewUserLoans() {


String query = "SELECT * FROM loans";
try (Connection conn = MySQLConnector.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query)) {
while (rs.next()) {
System.out.printf("Loan ID: %d, Account: %d, Type: %s,
Amount: %.2f, Interest: %.2f, Status: %s%n",
rs.getInt("loan_id"), rs.getInt("account_number"),
rs.getString("loan_type"),
rs.getDouble("loan_amount"), rs.getDouble("interest"),
rs.getString("status"));
}
} catch (SQLException e) {
System.out.println("Error retrieving loans: " + e.getMessage());
}
}

public void approveLoan() {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter Loan ID: ");
int loanId = scanner.nextInt();
System.out.print("Enter Approval Status (approved/rejected): ");
String status = scanner.next();

String query = "UPDATE loans SET status = ? WHERE loan_id


= ?";
try (Connection conn = MySQLConnector.getConnection();
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, status);
pstmt.setInt(2, loanId);
pstmt.executeUpdate();
System.out.println("Loan status updated successfully.");
} catch (SQLException e) {
System.out.println("Error updating loan status: " +
e.getMessage());
}
}
}

Transaction History Class:


class TransactionHistory {
public void viewTransactionHistory(int accountNumber) {
String query = "SELECT * FROM loans WHERE
account_number = ?";
try (Connection conn = MySQLConnector.getConnection();
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setInt(1, accountNumber);
try (ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
System.out.printf("Loan ID: %d, Type: %s, Amount: %.2f,
Interest: %.2f, Status: %s%n",
rs.getInt("loan_id"), rs.getString("loan_type"),
rs.getDouble("loan_amount"),
rs.getDouble("interest"), rs.getString("status"));
}
}
} catch (SQLException e) {
System.out.println("Error retrieving transaction history: " +
e.getMessage());
}
}
}

Main Program Class:


public class LoanManagementSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
AccountManager accountManager = new AccountManager();
LoanManager loanManager = new LoanManager();
TransactionHistory transactionHistory = new
TransactionHistory();

while (true) {
System.out.println("\n--- Main Menu ---");
System.out.println("1. Bank Manager");
System.out.println("2. User");
System.out.println("3. Exit");
System.out.print("Select an option: ");
int choice = scanner.nextInt();

switch (choice) {
case 1 -> {
boolean exitAdminMenu = false;
while (!exitAdminMenu) {
System.out.println("\n--- Manager Menu ---");
System.out.println("1. View All User Loans");
System.out.println("2. Set Interest Rate");
System.out.println("3. Approve Loan");
System.out.println("4. Back to Main Menu");
System.out.print("Select an option: ");
int adminChoice = scanner.nextInt();
switch (adminChoice) {
case 1 -> loanManager.viewUserLoans();
case 2 -> loanManager.selectInterestRate();
case 3 -> loanManager.approveLoan();
case 4 -> exitAdminMenu = true;
default -> System.out.println("Invalid choice.");
}
}
}
case 2 -> {
boolean exitUserMenu = false;
boolean loggedIn = false;
int accountNumber = -1;
while (!exitUserMenu) {
System.out.println("\n--- User Menu ---");
System.out.println("1. Create Account");
System.out.println("2. Login");
System.out.println("3. Apply for Loan");
System.out.println("4. View Loan History");
System.out.println("5. Back to Main Menu");
System.out.print("Select an option: ");
int userChoice = scanner.nextInt();
switch (userChoice) {
case 1 -> accountManager.createAccount();
case 2 -> {
loggedIn = accountManager.login();
if (loggedIn) {
System.out.print("Enter your account number:
");
accountNumber = scanner.nextInt();
}
}
case 3 -> {
if (loggedIn)
loanManager.applyForLoan(accountNumber);
else System.out.println("Please login first.");
}
case 4 -> {
if (loggedIn)
transactionHistory.viewTransactionHistory(accountNumber);
else System.out.println("Please login first.");
}
case 5 -> exitUserMenu = true;
default -> System.out.println("Invalid choice.");
}
}
}
case 3 -> {
System.out.println("Exiting the system. Goodbye!");
return;
}
default -> System.out.println("Invalid choice.");
}
}
}
}
ScreenShots :
Creating a new account by entering name, password,Phone
number, address, type of account :

Login the account that has been created :


Viewing the Loan History for the account that has been logged in :

Login as Bank Manager and viewing all the Loan taken by all bank
users :

Here it is seen that the status of approval is “pending” and Interest


is 0.00 for Loan ID :9 and Account no: 6
User apply for Loan and if credit score is below 800, it is rejected.
If it is above or equal to 800, the type of Loan that the user wills to
apply is displayed and user selects one.
Manager Sets interest rate for the User ( Variable Or Fixed ) and
Loan ID and the Loan of the User is approved by the Manager.
As the Manager approved the Loan , the “pending” status has been
changed to approved and Interest has been calculated.

Database ScreenShot:
Loan Management Database :
Loans Database:

10.References for Domain and Motivation(url):


https://techreviewer.co/
https://www.fintechfutures.com/
https://refactoring.guru/design-patterns/strategy
https://www.forbes.com/
Group Contribution Details:
KISHORE S:
Along with designing Strategy pattern , Kishore has following
contributions
• Responsibilities:
o Craft the problem statement, detailing the issues faced by
banking customers and the need for automation in the
banking sector.
o Write the motivation section, explaining why the project
was chosen, focusing on the relevance of design patterns
like Facade, Strategy, and Chain of Responsibility.
• Contribution: Ensure the context and justification for the project
are clearly articulated.
KAUSHIK K:
Along with designing Chain of responsibility pattern , Kaushik has
following contributions
• Responsibilities:
o Describe the domain of the project, explaining its focus on
the financial services industry and how design patterns
address the challenges in this domain.
o Elaborate on the involvement of each design pattern in the
project, detailing their purpose and implementation plan.
• Contribution: Highlight the technical and architectural aspects
of the project.
NARESH R:
Along with designing Facade pattern , Naresh has following
contributions
• Responsibilities:
o Review and refine the content contributed by the other
members to ensure clarity and coherence.
o Format the document according to the required guidelines,
ensuring it is well-structured and visually appealing.
o Compile and finalize the document, adding references and
ensuring all sections are complete.
• Contribution: Ensure the document is polished, well-organized,
and ready for submission.

You might also like