Проектирование и разработки библиотек классов
Автор: Dimitri WIGON • Апрель 13, 2022 • Лабораторная работа • 2,576 Слов (11 Страниц) • 214 Просмотры
Цель работы: приобрести навыки проектирования и разработки библиотек классов; изучить и приобрести навыки использования механизма сериализации объектов.
Ход работы
1. Исходный код
package com.company;
import java.io.*;
import java.util.ArrayList;
public class Main {
static SaverReader sr = new SaverReader();
public static void main(String[] args) {
ArrayList<Bank> bb = new ArrayList<Bank>();
Bank bank = new Bank("My bank");
Owner owner = new Owner("N1", "S1", "0");
Owner owner2 = new Owner("N2", "S2", "1");
bank.register(owner);
bank.register(owner2);
BankAccount acc1 = bank.openAccount(owner);
BankAccount acc2 = bank.openAccount(owner2);
try {
acc1.deposit(25);
acc1.transfer(15, acc2);
acc2.withdraw(30);
} catch (Exception e) {
System.out.println(e.getMessage());
}
String filename = "notes.dat";
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
oos.writeObject(bank);
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(bank.info());
Bank bank2 = new Bank("");
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
bank2 = (Bank) ois.readObject();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
System.out.println(bank2.info());
sr.addBanks(bank);
sr.addAccounts(acc1, acc2);
sr.addOwners(owner, owner2);
sr.save();
System.out.println("\nAuto load: \n");
sr.load();
System.out.println(sr.banks.get(0).info());
}
}
package com.company;
import java.io.Serializable;
import java.util.ArrayList;
public class Bank implements Serializable {
String name;
ArrayList<Owner> clients = new ArrayList<Owner>();
public Bank(String name) {
this.name = name;
};
public void register(Owner owner){
if(!clients.contains(owner)){
clients.add(owner);
}
}
public BankAccount openAccount(Owner owner){
if(clients == null || !clients.contains(owner)){
System.out.println("Registering user...");
this.register(owner);
}
BankAccount account = new BankAccount(owner);
owner.addAccount(account);
return account;
}
public String info(){
StringBuilder msg = new StringBuilder();
msg.append(name);
msg.append('\n');
for(Owner owner: clients){
msg.append('\t');
msg.append(owner.info());
msg.append(":\n");
for(BankAccount account: owner.getAccounts()){
msg.append("\t\t");
msg.append(account.info());
msg.append('\n');
}
}
return msg.toString();
}
}
package com.company;
import java.io.Serializable;
import java.util.ArrayList;
public class Owner implements Serializable
...