1. Description
First of all, from the actual life to understand the origin of the prototype model, if you have a very good handout, your friends want a copy, then how to do? Re-copy one? Obviously not, of course, copying a copy of the copier is convenient, straightforward, and high accuracy, this prototype to copy rather than re-create the way of thinking is the core idea of prototype mode.
Prototype pattern is also a creation pattern that focuses on the creation of a large number of identical or similar objects. The prototype pattern is to create a prototype and then copy the prototype to produce a new object that is identical or similar to the prototype, or to use a prototype instance to specify the kind of object to create, and to copy the prototypes to create new objects, such as resumes.
2. Code
function Table.deepcopy (object) Local lookup_table = {} local function _copy (object) if Type (object) ~= "Tabl E "then return to 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) does 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 = Nilse Lf. 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 ("Work experience:", 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", "+") a:setworkexperience ("", "" SQL ") a :D Isplay (); B = A:clone () b:setworkexperience ("n", "C + +");p rint ("------------**********----------------") A:display (); B:display () Endmain ()
run the results as follows:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Design pattern Instance (Lua) Note V (Prototype mode)