設計模式執行個體(Lua)筆記之五(Prototype 模式)

來源:互聯網
上載者:User

標籤:lua   設計模式   prototype   

1.描述

      

        首先從實際生活來瞭解原型模式的由來,假設你有一份非常好的講義,你的朋友也想要一份,那麼怎麼辦?重新手抄一份?顯然不是,當然是用複印機複印一份來得方便、直接,並且準確性也高,這種用原型來複製而不是重新建立的思維方式就是原型模式的核心思想。

  Prototype Pattern也是一種建立型模式,它關注的是大量相同或相似對象的建立問題。應用原型模式就是建立一個原型,然後通過對原型來進行複製的方法,來產生一個和原型相同或相似的新對象,或者說用原型執行個體指定建立對象的種類,並且通過複製這些原型建立新的對象,比如簡曆。

2.代碼

function table.deepcopy(object)    local lookup_table = {}    local function _copy(object)        if type(object) ~= "table" then            return object        elseif lookup_table[object] then            return lookup_table[object]        end        local new_table = {}        lookup_table[object] = new_table        for index, value in pairs(object) do            new_table[_copy(index)] = _copy(value)        end        return setmetatable(new_table, getmetatable(object))    end    return _copy(object)end--------Experience-------Experience = class()function Experience:ctor()self.timeArea = nilself.company = nilendfunction Experience:WorkExperience(timeArea, company)self.timeArea = timeAreaself.company = companyend--------Resume-------Resume = class()function Resume:ctor(name)self.name = nameself.sex  = nilself.age  = nilself.WorkExperience = Experience.new()endfunction Resume:SetPersonalInfo(sex, age)self.sex = sexself.age = ageendfunction Resume:SetWorkExperience(timeArea, company)self.WorkExperience:WorkExperience(timeArea, company)endfunction Resume:Display()print(self.name, " ", self.sex, " ", self.age)print("工作經曆:",self.WorkExperience.timeArea, "  ", self.WorkExperience.company)print("**********************")endfunction Resume:Clone()return table.deepcopy(self)end--- main ---function main()A = Resume.new("Rambo")A:SetPersonalInfo("M", "18")A:SetWorkExperience("2013", "SQL")A:Display();B = A:Clone()B:SetWorkExperience("2014","C++");print("------------**********----------------")A:Display();B:Display()endmain()


運行結果,如下:


      

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

設計模式執行個體(Lua)筆記之五(Prototype 模式)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.