您的位置:首页 > 编程语言 > MATLAB

MATLAB OOP 实例 : 一个简单的BankAccout类

2011-05-03 23:42 309 查看
该例来自MATLAB OOP user manual. 程序加入一些注释(部分采用了C++的一些术语)旨在用这个例子说明一些简单的MATLAB OOP 语法

BankAccount Class

% BandAccount.m 文件
classdef BankAccount < handle  %继承一个句柄基类 句柄类自动管理内存
properties (Hidden)        %使用Hidden关键词修饰属性 在MATLAB的类display中不会显示这个属性
%但是仍然具有public的属性,可以在外部直接访问
AccountStatus = 'open'
end

properties (SetAccess = private ) %SetAccess声明访问权限
%这里Private意味着该成员只能通过成员函数access
AccountNumber
AccountBalance = 0 ;
end

events                            %定义一个事件,叫做存款不足
InsufficientFunds
end

methods
%Constructor将接受初始化参数,返回一个新的obj

function BA = BankAccount(AccountNumber, InitialBalance)
BA.AccountNumber  = AccountNumber  ;
BA.AccountBalance = InitialBalance ;
AccountManager.addAccount(BA);
%在这里使用了AccountManager类的static方法,即不需要声明
%AccountManager对象就可以直接使用这个方法
end

%由于各个对象之间是共享成员函数的,所以需要通过参数列表把具体的obj传递
%给函数,在函数体内,访问成员变量也要加上obj的名字 这是nargin = 2
function deposit(BA, amt)                   %这个函数实际只接受一个参数

BA.AccountBalance = BA.AccountBalance + amt ;
if BA.AccountBalance > 0
BA.AccountStatus = 'open';
end
end

function withdraw(BA,amt)
if(strcmp (BA.AccountStatus ,'closed') && BA.AccountBalance<0 )
disp(['Account',num2str(BA.AccountNumber),'has been closed']);
return
end

newbal = BA.AccountBalance - amt ;
BA.AccountBalance = newbal ;

%如果newbal小于零,将触发一个InsufficientFunds事件,对象在这里是一个
%通知者,但是并没有注明将通知谁,register的过程在监听方完成
%这里是一个Observer Pattern
if newbal < 0
notify(BA,'InsufficientFunds')
%需要注明是哪个obj发出了这个通知
end
end

%使用缺省的析构函数
end
end


 

AccountManger Class

%  AccountManager.m
classdef AccountManager
methods (Static)                %静态方法,不需要实例化也可以使用其中函数
function assignStatus(BA)
if BA.AccountBalance < 0   %如果得到了合适的Reference
%这个经理类可以直接访问private属性
if BA.AccountBalance < -200
BA.AccountStatus = 'closed';
else
BA.AccountStatus = 'overdrawn';
end
end
end

function addAccount(BA)
%BA是继承自handle class
%addlistener是handle class的一个方法
addlistener(BA,'InsufficientFunds',...
@(src,events)AccountManager.assignStatus(src));

end
end
end


 

 

Driver.m

clear; format long ; format compact ;

BA = BankAccount(1234567,500);
BA.AccountNumber
BA.AccountBalance
BA.AccountStatus
BA.withdraw(600) %注意这个成员函数的调用方法
%没有使用BA.withdraw(BA,600)
%第一个参数是隐藏的
BA.AccountBalance
BA.AccountStatus

BA.withdraw(200)
BA.AccountBalance
BA.AccountStatus

BA.withdraw(100) %这时候不允许在取钱
%Balance应该freeze在-300
BA.AccountBalance

BA.deposit(900)
BA.AccountBalance
BA.AccountStatus

% 输出省略
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息