MATLAB Object-Oriented Programming

(Joyce) #1

AccountStatus
end
methods
function obj = BankAccount(initialBalance)
obj.AccountBalance = initialBalance;
obj.AccountStatus = 'New Account';
obj.AccountManagerListener = AccountManager.addAccount(obj);
end
end
methods (Static)
function obj = loadobj(obj)
if isstruct(obj) % Handle error
initialBalance = obj.AccountBalance;
obj = BankAccount(initialBalance);
else
obj.AccountManagerListener = AccountManager.addAccount(obj);
end
end
end
end


Assume the AccountManager class provides services for various types of accounts. For
the BankAccount class, the AccountManager class defines two Static methods:



  • assignStatus — Callback for the AccountBalance property PostSet listener. This
    method determines the value of the BankAccount AccountStatus property.

  • addAccount — Creates the AccountBalance property PostSet listener. The
    BankAccount constructor and loadobj methods call this method.


classdef AccountManager
methods (Static)
function assignStatus(BA,~)
if BA.AccountBalance < 0 && BA.AccountBalance >= -100
BA.AccountStatus = 'overdrawn';
elseif BA.AccountBalance < -100
BA.AccountStatus = 'frozen';
else
BA.AccountStatus = 'open';
end
end
function lh = addAccount(BA)
lh = addlistener(BA,'AccountBalance','PostSet', ...
@(src,evt)AccountManager.assignStatus(BA));
end


Restore Listeners
Free download pdf