Professional Documents
Culture Documents
Group: IT1-2107
Name: Seidygali Daryn
Proxy Pattern
The use of the Proxy pattern in a banking system aims to enhance security and
access control. The Proxy pattern creates an intermediary level that manages
requests to the actual object.
The Proxy server (BankProxy) controls access to methods of the real banking
service, allowing additional functionality or control without altering the existing
banking system's code.
### RealBankService
- Methods:
- `authenticateUser(int userId)` - authenticates the user in the banking system.
- `getAccountBalance(int userId)` - retrieves the user's account balance based
on their ID.
- `makeTransaction(int userId, double amount)` - conducts a transaction
(withdraws funds).
BankProxy
- Methods:
- `authenticateUser(int userId)` - delegates the authentication request to the
real banking service through `RealBankService`.
- `getAccountBalance(int userId)` - delegates the user's balance request to the
real banking service.
- `makeTransaction(int userId, double amount)` - delegates the transaction
request to the real banking service.
Transaction
- Description:
- This class stores information about transactions, such as the transaction ID,
user ID, and transaction amount.
User
- Description:
- This class represents a user with an identifier and name.
The program `BankExample` is an example of using these classes. It requests a
user's ID, authenticates via `BankProxy`, and then allows checking the user's
balance and making a transaction (withdrawing funds) using methods from
`RealBankService` through `BankProxy`.
CODE:
import java.util.Scanner;
if (isAuthenticated) {
System.out.println("Аутентификация прошла успешно.");
while (true) {
System.out.println("\nВыберите действие:");
System.out.println("1. Проверить баланс");
System.out.println("2. Совершить транзакцию");
System.out.println("3. Выйти");
switch (choice) {
case 1:
double balance =
bankProxy.getAccountBalance(userId);
System.out.println("Баланс пользователя: " +
balance);
break;
case 2:
System.out.print("Введите сумму для транзакции: ");
double transactionAmount = scanner.nextDouble();
scanner.nextLine(); // очистить буфер после ввода
числа
boolean isTransactionSuccessful =
bankProxy.makeTransaction(userId, transactionAmount);
if (isTransactionSuccessful) {
System.out.println("Транзакция на сумму " +
transactionAmount + " успешно проведена.");
} else {
System.out.println("Транзакция не выполнена.
Ошибка аутентификации или недостаточно средств.");
}
break;
case 3:
System.out.println("Программа завершена.");
scanner.close();
return;
default:
System.out.println("Неверный выбор. Попробуйте еще
раз.");
break;
}
}
} else {
System.out.println("Ошибка аутентификации. Доступ к операциям
запрещен.");
}
}
}
public class RealBankService implements BankService {
// Реализация интерфейса BankService для банковской системы
@Override
public boolean authenticateUser(int userId) {
// Логика аутентификации пользователя в реальной банковской системе
return true; // Пример: всегда возвращает true для упрощения
}
@Override
public double getAccountBalance(int userId) {
// Логика получения баланса пользователя из реальной банковской
системы
return balance;
}
@Override
public boolean makeTransaction(int userId, double amount) {
// Логика проведения транзакции в реальной банковской системе
if (balance >= amount) {
balance -= amount; // Вычитаем сумму транзакции из баланса
return true; // Транзакция выполнена успешно
} else {
return false; // Недостаточно средств на счете
}
}
}
public class Transaction {
private int transactionId;
private int userId;
private double amount;
}
public class BankProxy implements BankService {
private RealBankService realBankService; // Ссылка на реальный
банковский сервис
@Override
public boolean authenticateUser(int userId) {
return realBankService.authenticateUser(userId);
}
@Override
public double getAccountBalance(int userId) {
return realBankService.getAccountBalance(userId);
}
@Override
public boolean makeTransaction(int userId, double amount) {
// Вызов метода makeTransaction реального банковского сервиса
return realBankService.makeTransaction(userId, amount);
}
}
DIAGRAM: