lua-users home
lua-l archive

question?

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Exercise 21.4: A variation of the dual representation is to implement objects using proxies (the section called “Tracking table accesses”). Each object is represented by an empty proxy table. An internal table maps proxies to tables that carry the object state. This internal table is not accessible from the outside, but methods use it to translate their self parameters to the real tables where they operate. Implement the Account example using this approach and discuss its pros and cons.
this is my code:
-- Exercise 21.4 -- :
localAccountProxy= {}

localaccounts= {}
functionAccountProxy:new()
localproxy= {}
localaccount= {}
accounts[proxy] =account

setmetatable(proxy, {
__newindex=function(_, k, v)
account[k] =v
end,
__index=function(_, k)
returnaccount[k]
end,
})

returnproxy
end

functionAccountProxy:withdraw(v)
self.balance= (self.balanceor0) -v
end

functionAccountProxy:deposit(v)
self.balance= (self.balanceor0) +v
end

functionAccountProxy:getBalance()
returnself.balanceor0
end

-- Example usage
localacc_1=AccountProxy:new()
acc_1:deposit(100.0)
print(acc_1:getBalance()) -- 100.0
acc_1:withdraw(50.0)
print(acc_1:getBalance()) -- 50.0

AltStyle によって変換されたページ (->オリジナル) /