송금 기능
Coddy Lua 여정의 객체 지향 프로그래밍 (Object Oriented Programming) 섹션에 포함된 레슨. 70개 중 24번째.
챌린지
쉬움디지털 은행이 거의 완성되었습니다! 마지막 주요 기능은 계좌 간에 money를 transfer하는 기능입니다. 여기서 object-oriented 설계의 진가가 드러납니다. 하나의 계좌 객체가 다른 계좌 객체와 직접 상호 작용할 수 있기 때문입니다.
:transfer(targetAccount, amount) method를 추가하여 한 계좌에서 다른 계좌로 money를 이동하게 됩니다. 이 operation이 실제로 무엇을 포함하는지 생각해 보세요. source account에서 withdrawal을 수행한 다음 target account에 deposit하는 과정입니다. 이미 만든 method를 재사용할 수 있다는 점이 장점입니다!
기존 파일을 계속 확장하세요.
Account.lua: Account class에:transfer(targetAccount, amount)method를 추가하세요. 이 method는self에서 amount를 withdraw하려고 시도하고, successful하면 해당 amount를targetAccount에 deposit해야 합니다. withdrawal이 실패하면(Insufficient funds) transfer가 발생해서는 안 됩니다. 기존의 모든 기능(constructor with ID, deposit, withdraw, getBalance, __tostring)을 유지하세요.main.lua: 여러 account를 만들고 account 객체 간의 transfer를 보여 주면서 서로 다른 account 객체의 balance가 어떻게 변하는지 나타내세요.
다섯 개의 inputs를 받습니다.
- first account의 ID
- second account의 ID
- first account에 대한 initial deposit
- first transfer amount (account 1에서 account 2로)
- second transfer amount (account 1에서 account 2로)
main file에서 given IDs로 두 개의 account를 만드세요(둘 다 balance 0에서 시작). initial amount를 first account에 deposit한 다음, first account에서 second account로 두 번의 transfer를 모두 시도하세요. 각 transfer attempt 후 두 account를 모두 print하세요(__tostring이 current state를 보여 줍니다).
예를 들어 inputs가 101, 102, 500, 200, 400이면 output은 다음과 같아야 합니다.
Account [101]: Balance = 300
Account [102]: Balance = 200
Insufficient funds
Account [101]: Balance = 300
Account [102]: Balance = 200deposit 후 first account는 500으로 시작합니다. first transfer인 200은 successful하여 account 101에는 300이, account 102에는 200이 남습니다. second transfer인 400은 account 101에 300만 있기 때문에 실패하므로 두 balance는 변경되지 않습니다.
직접 해보기
-- Account 모듈을 불러옵니다
local Account = require('Account')
-- 다섯 개의 입력을 읽습니다
local id1 = io.read()
local id2 = io.read()
local initialDeposit = tonumber(io.read())
local transfer1 = tonumber(io.read())
local transfer2 = tonumber(io.read())
-- ID로 두 개의 계정을 생성합니다
local account1 = Account:new(id1)
local account2 = Account:new(id2)
-- 첫 번째 계정에 초기 금액을 입금합니다
account1:deposit(initialDeposit)
-- TODO: account1에서 account2로 첫 번째 이체를 시도합니다
-- TODO: 첫 번째 이체 후 두 계정을 모두 출력합니다
-- TODO: account1에서 account2로 두 번째 이체를 시도합니다
-- TODO: 두 번째 이체 후 두 계정을 모두 출력합니다
객체 지향 프로그래밍 (Object Oriented Programming)의 모든 레슨
직접 연습해 보세요: 온라인 Lua 컴파일러