
;; Proxy folds into a delay: the real subject is built at the first deref
;; and never before, so cheap questions cost nothing
;; RealSubject - expensive to make
(defn image [file-name]
(println "loading" file-name)
{:file-name file-name
:draw #(println "draw" file-name)}) ; Request()
;; Proxy - holds the cheap part and a promise of the real one
(defn image-proxy [file-name]
{:file-name file-name
:image (delay (image file-name))})
;; Client
(def p (image-proxy "1.png"))
(println (:file-name p)) ; answered without creating the RealSubject
((:draw @(:image p))) ; now the RealSubject is created
;; 1.png
;; loading 1.png
;; draw 1.png
Provide a surrogate or placeholder for another object to control access to it. The proxy implements the interface of the original object.Read more问题。一份文档包含许多大图。如果程序在打开文档时就加载所有图片,打开会很慢,尽管用户只看到第一页。显示图片的代码应当保持不变,但加载必须推迟到真正需要某张图片时。 思路。代理代替另一个对象,即真实对象。两者接口相同,因此客户端看不出它们的区别。代理决定何时以及如何使用真实对象。这里的代理属于虚拟代理:它只在第一次请求时创建真实对象,之后把每次调用都转发给它。其他种类的代理会检查访问权限、维护缓存,或者访问另一台计算机上的对象。 如何阅读示例。真实对象是一张创建代价高昂的图像。代理只保存文件名,并为图像留出一个空位。在大多数语言中,客户端先询问文件名,代理自己就能回答。当客户端要求绘制时,代理创建真实的图像,保存下来并转发这次调用。客户端始终只与代理打交道。在某些语言中,输出还会显示真实图像被加载的时刻。 何时使用。要控制对某个对象的访问、又不改变该对象及其客户端时,使用代理模式。典型的任务有:推迟代价高昂的创建、检查权限、统计调用次数。对象创建代价低廉而且总是需要时,不要使用它:多出的一层只会拖慢代码。 常见错误。没有保存已创建的对象。这样代理每次调用都会创建一个新的真实对象,节省也就无从谈起。 |