Professional Documents
Culture Documents
Lab 8
Lab 8
Decorator Pattern
This code is an example of using the Decorator pattern in Java to model a bank
account with various additional functionalities, such as interest calculation and
commission charges. Let's break down the code step by step and explain how it
works in simple terms.
1. Interface BankAccount:
- Defines the basic interface for a bank account with a single method
`getBalance()`, which returns the current account balance.
2. Class BasicAccount:
- Implements the BankAccount interface.
- Represents the basic bank account with an initial balance specified when the
account is created.
- The `getBalance()` method returns the current account balance.
3. Class InterestDecorator:
- Extends the BankAccount interface.
- This class is a decorator that adds the functionality of calculating interest to
an existing bank account.
- When the `getBalance()` method is called, it retrieves the current balance
from the base account, multiplies it by the interest rate, and returns the new
balance.
4. Class CommissionDecorator:
- Extends the BankAccount interface.
- This class is also a decorator that adds the functionality of charging a
commission to an existing bank account.
- When the `getBalance()` method is called, it retrieves the current balance
from the base account, subtracts the commission (a percentage of the balance),
and returns the new balance.
As a result of running the program, you will get the final balance, taking into
account the initial balance, interest calculation, and commission charges,
depending on the values entered by the user. This demonstrates how the
Decorator pattern allows you to add various functionalities to an object without
changing its core structure.
CODE
import java.util.Scanner;
interface BankAccount {
double getBalance();
}
class BasicAccount implements BankAccount {
private double balance;
public BasicAccount(double balance) {
this.balance = balance;
}
@Override
public double getBalance() {
return balance;
}
}
class CommissionDecorator implements BankAccount {
private BankAccount account;
private double commissionRate;
@Override
public double getBalance() {
double balance = account.getBalance();
return balance - (balance * commissionRate);
}
}
class InterestDecorator implements BankAccount {
private BankAccount account;
private double interestRate;
@Override
public double getBalance() {
double balance = account.getBalance();
return balance * (1 + interestRate);
}
}
DIAGRAM