代理

设计模式 / 结构型模式
image

local images_created = 0

-- RealSubject
local Image = {}
Image.__index = Image

function Image.new(file_name)
  images_created = images_created + 1
  return setmetatable({file_name = file_name},
                      Image)
end

-- Request()
function Image:draw()
  return "draw " .. self.file_name
end

-- Proxy: the same field and method names;
-- the image is created on the first draw
local ImageProxy = {}
ImageProxy.__index = ImageProxy

function ImageProxy.new(file_name)
  return setmetatable({file_name = file_name},
                      ImageProxy)
end

function ImageProxy:draw()
  self.image = self.image
               or Image.new(self.file_name)
  return self.image:draw()
end

-- Client
local proxy = ImageProxy.new("1.png")
-- No image is needed to answer this
local file_name = proxy.file_name
-- file_name = 1.png
local created_before = images_created
-- created_before = 0

-- The call is passed to the image
local drawn = proxy:draw()
-- drawn = draw 1.png
-- images_created = 1

print("file_name = " .. file_name)
print("created_before = " .. created_before)
print("drawn = " .. drawn)
print("images_created = " .. images_created)


Provide a surrogate or placeholder for another object to control access to it. The proxy implements the interface of the original object.
Read more

问题。一份文档包含许多大图。如果程序在打开文档时就加载所有图片,打开会很慢,尽管用户只看到第一页。显示图片的代码应当保持不变,但加载必须推迟到真正需要某张图片时。

思路。代理代替另一个对象,即真实对象。两者接口相同,因此客户端看不出它们的区别。代理决定何时以及如何使用真实对象。这里的代理属于虚拟代理:它只在第一次请求时创建真实对象,之后把每次调用都转发给它。其他种类的代理会检查访问权限、维护缓存,或者访问另一台计算机上的对象。

如何阅读示例。真实对象是一张创建代价高昂的图像。代理只保存文件名,并为图像留出一个空位。在大多数语言中,客户端先询问文件名,代理自己就能回答。当客户端要求绘制时,代理创建真实的图像,保存下来并转发这次调用。客户端始终只与代理打交道。在某些语言中,输出还会显示真实图像被加载的时刻。

何时使用。要控制对某个对象的访问、又不改变该对象及其客户端时,使用代理模式。典型的任务有:推迟代价高昂的创建、检查权限、统计调用次数。对象创建代价低廉而且总是需要时,不要使用它:多出的一层只会拖慢代码。

常见错误。没有保存已创建的对象。这样代理每次调用都会创建一个新的真实对象,节省也就无从谈起。