標籤:
需求:
股民買賣股票
初步代碼:
# -*- encoding: utf-8 -*-#股票1class Stock1 def buy puts ‘股票1買入‘ end def sell puts ‘股票1賣出‘ endend#股票2class Stock2 def buy puts ‘股票2買入‘ end def sell puts ‘股票2賣出‘ endend#股票3class Stock3 def buy puts ‘股票3買入‘ end def sell puts ‘股票3賣出‘ endend#國債1class NationalDebt1 def buy puts ‘國債1買入‘ end def sell puts ‘國債1賣出‘ endend#房地產1class Realty1 def buy puts ‘房地產1買入‘ end def sell puts ‘房地產1賣出‘ endends1 = Stock1.news2 = Stock2.news3 = Stock3.newn1 = NationalDebt1.newr1 = Realty1.news1.buys2.buys3.buyn1.buyr1.buys1.sells2.sells3.selln1.sellr1.sell
問題:
可以發現使用者需要瞭解股票、國債、房產情況,需要參與這些項目的具體買和賣,耦合性很高。
改進代碼
# -*- encoding: utf-8 -*-#股票1class Stock1 def buy puts ‘股票1買入‘ end def sell puts ‘股票1賣出‘ endend#股票2class Stock2 def buy puts ‘股票2買入‘ end def sell puts ‘股票2賣出‘ endend#股票3class Stock3 def buy puts ‘股票3買入‘ end def sell puts ‘股票3賣出‘ endend#國債1class NationalDebt1 def buy puts ‘國債1買入‘ end def sell puts ‘國債1賣出‘ endend#房地產1class Realty1 def buy puts ‘房地產1買入‘ end def sell puts ‘房地產1賣出‘ endend#基金類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 endendf1 = Fund.newf1.buyf1.sell
好處:使用者不需要瞭解各種股票,只需購買賣出基金即可。
面板模式:
為子系統中的一組介面提供一個一致的介面,此模式定義了一個高層介面,這個介面使得這一子系統更加容易使用。
《大話設計模式》ruby版代碼:面板模式