Restore Listeners
Create Listener with loadobj
Suppose that you create a property listener and want to be able to save and restore the event source and the listener. One approach is to create a listener from the loadobj
method.
Use Transient Property to Load Listener
The BankAccount
class stores the account balance and an account status. A PostSet
listener attached to the AccountBalance
property controls the account status.
When the AccountBalance
property value changes, the listener callback determines the account status. Important points include:
The
BankAccount
class defines theAccountManagerListener
property to contain the listener handle. This property enables theloadobj
method to create a listener and return a reference to it in the object that is loaded into the workspace.The
AccountManagerListener
property isTransient
because there is no need to store the listener handle with aBankAccount
object. Create a listener that is attached to the newBankAccount
object created during the load process.The
AccountBalance
listener sets theAccountStatus
.Only the
AccountManager
class can accessAccountStatus
property.
classdef BankAccount < handle properties (SetObservable, AbortSet) AccountBalance end properties (Transient) AccountManagerListener end properties (Access = ?AccountManager) 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 theAccountBalance
propertyPostSet
listener. This method determines the value of theBankAccount
AccountStatus
property.addAccount
— Creates theAccountBalance
propertyPostSet
listener. TheBankAccount
constructor andloadobj
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 end end
Using the BankAccount and AccountManager Classes
Create an instance of the BankAccount
class.
ba = BankAccount(100)
ba = BankAccount with properties: AccountBalance: 100 AccountManagerListener: [1x1 event.proplistener] AccountStatus: 'New Account'
Now set an account value to confirm that the AccountManager
sets AccountStatus
appropriately:
ba.AccountBalance = -10; ba.AccountStatus
ans = overdrawn