<aside> 💡 트랜잭션 = 데이터의 상태를 변환하기위한 일의 최소단위
</aside>
<aside> 💡 메서드는 하나의 책임만 가지는게 좋다.
</aside>
package ex04.example.model;
//객체의 상태를 변경, 객체의 상태를 확인
public class Account {
private final int id;
private long balance;
private int userId;
public boolean 잔액부족하니(long amount) {
if (balance < amount) {
return true;
}
return false;
}
//메서드는 하나의 책임만 가지는게 좋다.
public void 출금(long amount) {
this.balance = this.balance - amount;
}
public void 입금(long amount) {
this.balance = this.balance + amount;
}
public Account(int id, long balance, int userId) {
this.id = id;
this.balance = balance;
this.userId = userId;
}
@Override
public String toString() {
return "Account{" +
"id = " + id +
", balance = " + balance +
", userId = " + userId +
'}';
}
}
package ex04.example.model;
public class User {
private final int id;
private String name;
private String email;
public User(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id= " + id +
", name= '" + name + '\\'' +
", email= '" + email + '\\'' +
'}';
}
}
package ex04.example;
import ex04.example.model.Account;
import ex04.example.model.User;
public class BankApp {
public static void main(String[] args) {
// 1. 고객 만들기
User ssar = new User(1, "ssar", "[email protected]");
User cos = new User(2, "cos", "[email protected]");
User love = new User(2, "love", "[email protected]");
// 2. 계좌 만들기
Account ssarAccount = new Account(1111, 1000L, 1);
Account cosAccount = new Account(2222, 1000L, 2);
Account loveAccount = new Account(3333, 1000L, 3);
// 3. 고객에게 정보를 받기 (sender, receiver, amount)
long amount = 100L; // 이체할 돈
// 4. 이체
BankService.이체(cosAccount, loveAccount, amount);
System.out.println(cosAccount);
System.out.println(loveAccount);
// 5. 출금
BankService.출금(ssarAccount, 100L);
System.out.println(ssarAccount);
}
}
package ex04.example;
import ex04.example.model.Account;
// 트랜잭션 관리
public class BankService {
public static void 출금(Account withdrawAccount, long amount) {
if (amount <= 0) {
System.out.println("0원 이하 금액을 출금할 수 없습니다.");
return;
}
if (withdrawAccount.잔액부족하니(amount)) {
System.out.println("잔액이 부족합니다.");
return;
}
withdrawAccount.출금(amount);
}
public static void 이체(Account senderAccount, Account receiverAccount, long amount) {
if (amount <= 0) {
System.out.println("0원 이하 금액을 이체할 수 없습니다.");
return;
}
if (senderAccount.잔액부족하니(amount)) {
System.out.println("잔액이 부족합니다.");
return;
}
senderAccount.출금(amount);
receiverAccount.입금(amount);
}
}