設計模式實例(Lua)筆記之七(Decorator模式)
阿新 • • 發佈:2017-06-08
部分 才幹 mark ack 我沒 () str div new
執行結果:
1.描寫敘述
就說說"我"上小學的的糗事吧。
我上小學的時候學習成績非常的差,班級上 40 多個同學,我基本上都是在排名 45 名以後,依照老師給我的定義就是“不是讀書的料”,可是我老爸管的非常嚴格,明知道我不是這塊料,還是往趕鴨子上架,每次考試完成我都是戰戰兢兢的,“竹筍炒肉”是肯定少不了的,能少點就少點吧,肉可是自己的呀。
四年級期末考試考完,學校出來個非常損的招兒(這招兒如今非常流行的),打印出成績單,要家長簽字,然後才幹上五年級,我那個恐懼呀,只是也就是幾秒鐘的時間,玩起來什麽都忘記了。當時。我的成績(語文 62 數學65 體育 98 自然 63),你要知道在小學低於 90 分基本上就是中下等了,唉,愛學習的人太多了!怎麽著,那我把這個成績單給老爸看看?
就這成績還要我簽字?
!老爸就開始找笤帚,我的屁股已經做好了準備,肌肉要繃緊,要不那個太疼了!哈哈,幸運的是,這個不是當時的真實情況,我沒有直接把成績單交給老爸,而是在交給他之前做了點技術工作,我要把成績單封裝一下,封裝分類兩步走:
第一步:跟老爸說各個科目的最高分,語文最高是 75,數學是 78,自然是 80,然老爸覺的我成績與最高分數相幾乎相同,這個是實情,可是不知道是什麽原因,反正期末考試都考的不怎麽樣,可是基本上都集中在 70 分以上,我這 60 多分基本上還是墊底的角色;
第二步:在老爸看成績單後,告訴他我是排名第 38 名,全班,這個也是實情,為啥呢?
有將近十個同學退學了!這個情況我是不說的。不知道是不是當時第一次發成績單,學校沒有考慮清楚,沒有寫上總共同擁有多少同學,排名第幾名等等,反正是被我鉆了個空子。類圖例如以下:
2.代碼
require "class" --------ISchoolReport------- ISchoolReport = class() function ISchoolReport:Report() end function ISchoolReport:Sign(name) end --------FouthGradeSchoolReport------- FouthGradeSchoolReport = class(ISchoolReport) function FouthGradeSchoolReport:Report() print("----------FouthGradeSchoolReport:Report-----------") print("尊敬的XXX家長:") print(".......") print("語文62 數學65 體育98 自然63") print(".......") print(" 家長簽名:") end function FouthGradeSchoolReport:Sign(name) print("家長簽名為:", name) end --------ReportDecorator------- ReportDecorator = class(ISchoolReport) function ReportDecorator:ctor(psr) self.m_pSchoolReport = psr end function ReportDecorator:IReport() print("----------ReportDecorator:IReport-----------") self.m_pSchoolReport:Report() end function ReportDecorator:Sign(name) self.m_pSchoolReport:Sign(name) end --------HighScoreDecorator------- HighScoreDecorator = class(ReportDecorator) function HighScoreDecorator:Report() print("----------HighScoreDecorator:Report-----------") self:ReportHighScore() self:IReport() end function HighScoreDecorator:ReportHighScore() print("這次考試語文最高是75, 數學是78, 自然是80") end --------SortDecorator------- SortDecorator = class(ReportDecorator) function SortDecorator:ReportSort() print("我是排名第38名...") end function SortDecorator:Report() print("----------SortDecorator:Report-----------") self:IReport() self:ReportSort() end --------test------- function DoIt() local psr = FouthGradeSchoolReport.new() psr:Report() psr:Sign("老三") end function DoNew() print("----------分部分進行裝飾----------") local psr = FouthGradeSchoolReport.new() -- 原裝成績單 local pssr = SortDecorator.new(psr) -- 又加了成績排名的說明 local phsr = HighScoreDecorator.new(pssr) -- 加了最高分說明的成績單 phsr:Report() phsr:Sign("老三") end --- main --- function main() --DoIt() DoNew() end main()
設計模式實例(Lua)筆記之七(Decorator模式)