Refactor class structure: redefine BankAccount and PremiumAccount classes, remove Vault and SubVault implementations

This commit is contained in:
Chipperfluff 2026-01-01 17:48:03 +01:00
parent 1a492d9b9a
commit 83fde73df8

View File

@ -1,48 +1,59 @@
oop = require("oop/oop") oop = require("oop/oop")
function Vault(cls) function BankAccount(cls)
cls.setattr(cls, "public_note", nil, "public") cls.setattr(cls, "owner", nil, cls.visibility.PUBLIC)
cls.setattr(cls, "protected_note", nil, "protected") cls.setattr(cls, "balance", nil, cls.visibility.PUBLIC)
cls.setattr(cls, "private_note", nil, "private") cls.setattr(cls, "pin", nil, cls.visibility.PROTECTED)
cls.setattr(cls, "token", nil, cls.visibility.PRIVATE)
cls.method("public_method", function(this) cls.method("deposit", function(this, amount)
print("public_method:", this.public_note) this.balance = this.balance + amount
end, "public") print("deposit:", amount, "balance:", this.balance)
end, cls.visibility.PUBLIC)
cls.method("protected_method", function(this) cls.method("withdraw", function(this, amount, pin)
print("protected_method:", this.protected_note) if pin ~= this.pin then
end, "protected") print("bad pin")
return
end
this.balance = this.balance - amount
print("withdraw:", amount, "balance:", this.balance)
end, cls.visibility.PUBLIC)
cls.method("private_method", function(this) cls.method("audit", function(this)
print("private_method:", this.private_note) print("audit:", this.owner, "balance:", this.balance)
end, "private") end, cls.visibility.PROTECTED)
function cls.__init(this) cls.method("rotate_token", function(this)
this.public_note = "hello" this.token = "t-" .. tostring(os.time())
this.protected_note = "shielded" print("token rotated")
this.private_note = "secret" end, cls.visibility.PRIVATE)
function cls.__init(this, owner, pin)
this.owner = owner
this.balance = 0
this.pin = pin
this.token = "t-" .. tostring(os.time())
end end
end end
function SubVault(cls) function PremiumAccount(cls)
cls.inherit(Vault) cls.inherit(BankAccount)
function cls.show_all(this) function cls.monthly_bonus(this)
print("inside SubVault:") this.deposit(25)
this.public_method() this.audit()
this.protected_method()
this.private_method()
end end
end end
local v = oop.new(Vault) local acct = oop.new(BankAccount, "Kim", 1234)
print("outside Vault:") acct.deposit(100)
print("public_note:", v.public_note) acct.withdraw(30, 1234)
v.public_method()
print("protected_note:", v.protected_note)
print("private_note:", v.private_note)
v.protected_method()
v.private_method()
local s = oop.new(SubVault) local vip = oop.new(PremiumAccount, "Sam", 9999)
s.show_all() vip.monthly_bonus()
local ok, err = pcall(function()
vip.rotate_token()
end)
print("rotate_token from outside:", ok, err)