
-- ConcretePrototype
local Square = {}
Square.__index = Square
function Square.new(color)
return setmetatable({color = color}, Square)
end
-- A new table with the same fields
-- and the same class
function Square:clone()
local copy = {}
for key, value in pairs(self) do
copy[key] = value
end
return setmetatable(copy, getmetatable(self))
end
-- Client: makes shapes from a prototype
-- without naming its class
local function shape_maker(shape)
return function()
return shape:clone()
end
end
local square = Square.new("Red")
local make_shape = shape_maker(square)
local square1 = make_shape()
local square2 = make_shape()
local same = square1 == square2
-- same = false
-- No copy at all: an empty table that reads
-- missing fields from the prototype
local linked =
setmetatable({}, {__index = square})
-- It follows the prototype, a clone does not
square.color = "Blue"
-- linked.color = Blue
-- square1.color = Red
print("same = " .. tostring(same))
print("linked.color = " .. linked.color)
print("square1.color = " .. square1.color)
Specify the kinds of objects to create using a prototypical instance, and create new objectsby copying this prototype.Read more问题。绘图程序有一个现成图形的调色板,每个图形都有自己的颜色、大小和边框。用户把图形拖到页面上时,程序必须生成一个与之完全相同的新图形。如果代码使用构造函数,就必须知道确切的类,并手动复制每一项设置。于是每增加一种图形,这段代码都要修改。 思路。原型是一个知道如何复制自己的现成对象。它有一个复制方法,通常叫作 clone。客户端保存一个原型,并向它索要副本。客户端不指明具体类,也不知道复制了哪些字段。副本最初拥有与原件相同的数据,此后两个对象彼此独立。 如何阅读示例。原型是一个带有一个值的图形,这个值例如颜色或边数。在大多数语言中,一个客户端对象保存一个原型,只通过向它索要副本来生成新图形。输出显示副本的值与原型相同。有些示例还表明,副本是一个独立的对象,或者修改副本不会改变原型。在值永不改变的语言中,什么也不复制:变体就是改动了一个字段的同一样本。 何时使用。当对象的准备工作代价高昂、又需要许多相似的对象时,使用原型模式。当要创建的类要到程序运行时才能确定时,它也有帮助。字段不多的简单对象不要使用它:构造函数更简单。 常见错误。只在基类中编写复制方法,使它总是创建基类对象。这样,具体原型的副本就丢失了自己的类。每个具体原型都必须创建自己类的对象。 |