You are on page 1of 5

Documentation

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;

public class BankExample {


public static void main(String[] args) {
RealBankService realBankService = new RealBankService(); //
Создание реального банковского сервиса
BankProxy bankProxy = new BankProxy(realBankService); // Создание
прокси-сервера

Scanner scanner = new Scanner(System.in);

System.out.print("Введите идентификатор пользователя: ");


int userId = scanner.nextInt();
scanner.nextLine(); // очистить буфер после ввода числа

boolean isAuthenticated = bankProxy.authenticateUser(userId);

if (isAuthenticated) {
System.out.println("Аутентификация прошла успешно.");

while (true) {
System.out.println("\nВыберите действие:");
System.out.println("1. Проверить баланс");
System.out.println("2. Совершить транзакцию");
System.out.println("3. Выйти");

int choice = scanner.nextInt();


scanner.nextLine(); // очистить буфер после ввода числа

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 для банковской системы

private double balance = 1000.0; // Пример фиктивного баланса

@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 Transaction(int transactionId, int userId, double amount) {


this.transactionId = transactionId;
this.userId = userId;
this.amount = amount;
}

public int getTransactionId() {


return transactionId;
}
public void setTransactionId(int transactionId) {
this.transactionId = transactionId;
}

public int getUserId() {


return userId;
}

public void setUserId(int userId) {


this.userId = userId;
}

public double getAmount() {


return amount;
}

public void setAmount(double amount) {


this.amount = amount;
}
}
public class User {
private int userId;
private String username;

public User(int userId, String username) {


this.userId = userId;
this.username = username;
}

public int getUserId() {


return userId;
}

public void setUserId(int userId) {


this.userId = userId;
}

public String getUsername() {


return username;
}

public void setUsername(String username) {


this.username = username;
}
}
public interface BankService {
boolean authenticateUser(int userId);
double getAccountBalance(int userId);
boolean makeTransaction(int userId, double amount);

}
public class BankProxy implements BankService {
private RealBankService realBankService; // Ссылка на реальный
банковский сервис

public BankProxy(RealBankService realBankService) {


this.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:

You might also like