标签:
需求:
股民买卖股票
初步代码:
# -*- encoding: utf-8 -*- #股票1 class Stock1 def buy puts ‘股票1买入‘ end def sell puts ‘股票1卖出‘ end end #股票2 class Stock2 def buy puts ‘股票2买入‘ end def sell puts ‘股票2卖出‘ end end #股票3 class Stock3 def buy puts ‘股票3买入‘ end def sell puts ‘股票3卖出‘ end end #国债1 class NationalDebt1 def buy puts ‘国债1买入‘ end def sell puts ‘国债1卖出‘ end end #房地产1 class Realty1 def buy puts ‘房地产1买入‘ end def sell puts ‘房地产1卖出‘ end end s1 = Stock1.new s2 = Stock2.new s3 = Stock3.new n1 = NationalDebt1.new r1 = Realty1.new s1.buy s2.buy s3.buy n1.buy r1.buy s1.sell s2.sell s3.sell n1.sell r1.sell
问题:
可以发现用户需要了解股票、国债、房产情况,需要参与这些项目的具体买和卖,耦合性很高。
改进代码
# -*- encoding: utf-8 -*- #股票1 class Stock1 def buy puts ‘股票1买入‘ end def sell puts ‘股票1卖出‘ end end #股票2 class Stock2 def buy puts ‘股票2买入‘ end def sell puts ‘股票2卖出‘ end end #股票3 class Stock3 def buy puts ‘股票3买入‘ end def sell puts ‘股票3卖出‘ end end #国债1 class NationalDebt1 def buy puts ‘国债1买入‘ end def sell puts ‘国债1卖出‘ end end #房地产1 class Realty1 def buy puts ‘房地产1买入‘ end def sell puts ‘房地产1卖出‘ end end #基金类 class Fund attr_accessor s1, s2, s3, n1, r1 def initialize s1 = Stock1.new s2 = Stock2.new s3 = Stock3.new n1 = NationalDebt1.new r1 = Realty1.new end def buy s1.buy s2.buy s3.buy n1.buy r1.buy end def sell s1.sell s2.sell s3.sell n1.sell r1.sell end end f1 = Fund.new f1.buy f1.sell
好处:用户不需要了解各种股票,只需购买卖出基金即可。
外观模式:
为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
标签:
原文地址:http://www.cnblogs.com/fanxiaopeng/p/4224914.html