Demand:
Xiao Ming let Xiao Li Chase for him (send doll, send flowers, send chocolate)
Code with no proxy:
#-*-encoding:utf-8-*-#Suitor ClassclassPursuit attr_accessor:mmdefInitialize (mm) @mm=mm EnddefGive_dolls puts"#{mm.name} give you a doll"EnddefGive_flowers puts"#{mm.name} send you flowers"EnddefGive_chocolate puts"#{mm.name} give you chocolate"EndEnd#The pursued person classclassGirl Attr_accessor:namedefInitialize (name) @name=name Endendxiao_hong= Girl.new ('Little Red') xiao_ming=pursuit.new (xiao_hong) xiao_ming.give_dollsxiao_ming.give_flowersxiao_ming.give_chocolate
Only the agent's code:
#-*-encoding:utf-8-*-#proxy classclassProxy attr_accessor:mmdefInitialize (mm) @mm=mm EnddefGive_dolls puts"#{mm.name} give you a doll"EnddefGive_flowers puts"#{mm.name} send you flowers"EnddefGive_chocolate puts"#{mm.name} give you chocolate"EndEnd#The pursued person classclassGirl Attr_accessor:namedefInitialize (name) @name=name Endendxiao_hong= Girl.new ('Little Red') xiao_ming=proxy.new (xiao_hong) xiao_ming.give_dollsxiao_ming.give_flowersxiao_ming.give_chocolate
Just replaced the suitor class with the proxy class.
The actual proxy mode code:
#-*-encoding:utf-8-*-#public Interface ModuleModule GivegiftdefGive_dolls EnddefGive_flowers Enddefgive_chocolate endend#Suitor ClassclassPursuit include Givegift attr_accessor:mm,: NamedefInitialize (mm) @mm=mm EnddefGive_dolls puts"#{mm.name} to give you a doll for #{name}"EnddefGive_flowers puts"#{mm.name} give you flowers for #{name}"EnddefGive_chocolate puts"#{mm.name} give you chocolates for #{name}"EndEnd#proxy classclassProxy include Givegift attr_accessor:ggdefInitialize (mm) @gg=pursuit.new (mm) Enddefgive_dolls Gg.give_dolls Enddefgive_flowers Gg.give_flowers Enddefgive_chocolate gg.give_chocolate endend#The pursued person classclassGirl Attr_accessor:namedefInitialize (name) @name=name Endendxiao_hong= Girl.new ('Little Red') xiao_ming=proxy.new (xiao_hong) xiao_ming.gg.name='Xiao Ming'xiao_ming.give_dollsxiao_ming.give_flowersxiao_ming.give_chocolate
Proxy mode: provides a proxy for other objects to control access to this object.
Application Scenarios:
Provides a local representation of an object at different addresses so that it can hide the fact that an object exists in a different address space.
is to create expensive objects as needed. It is the real object that takes a long time to store the instantiation.
Used to control permissions that are true for object access.
When a real object is called, the agent handles something else.
"Big talk design mode" Ruby version code: Proxy mode