10

处理对象的多种状态及其相互转换——状态模式(三)

 3 years ago
source link: https://blog.csdn.net/LoveLion/article/details/8523083
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

处理对象的多种状态及其相互转换——状态模式(三)

3 完整解决方案

       Sunny软件公司开发人员使用状态模式来解决账户状态的转换问题,客户端只需要执行简单的存款和取款操作,系统根据余额将自动转换到相应的状态,其基本结构如图4所示:

图4 银行账户结构图

       在图4中,Account充当环境类角色,AccountState充当抽象状态角色,NormalState、OverdraftState和RestrictedState充当具体状态角色。完整代码如下所示:

温馨提示:代码有点长,需要有耐心!大笑

       编写如下客户端测试代码:

       编译并运行程序,输出结果如下:

段誉开户,初始金额为0.0

---------------------------------------------

段誉存款1000.0

现在余额为1000.0

现在帐户状态为NormalState

---------------------------------------------

段誉取款2000.0

现在余额为-1000.0

现在帐户状态为OverdraftState

---------------------------------------------

段誉存款3000.0

现在余额为2000.0

现在帐户状态为NormalState

---------------------------------------------

段誉取款4000.0

现在余额为-2000.0

现在帐户状态为RestrictedState

---------------------------------------------

段誉取款1000.0

帐号受限,取款失败

现在余额为-2000.0

现在帐户状态为RestrictedState

---------------------------------------------

计算利息!

【作者:刘伟 http://blog.csdn.net/lovelion


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK