码迷,mamicode.com
首页 > 其他好文 > 详细

《大话设计模式》ruby版代码:代理模式

时间:2015-01-02 19:50:40      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:

需求:

小明让小李替他追小丽(送洋娃娃,送花,送巧克力)

没有代理的代码:

# -*- encoding: utf-8 -*-

#追求者类
class Pursuit
    attr_accessor :mm
    
    def initialize(mm)
        @mm = mm
    end
    
    def give_dolls
        puts "#{mm.name} 送你洋娃娃"
    end
    
    def give_flowers
        puts "#{mm.name} 送你鲜花"
    end
    
    def give_chocolate
        puts "#{mm.name} 送你巧克力"
    end

end

#被追求者类
class Girl
    attr_accessor :name
    
    def initialize(name)
        @name = name
    end
end

xiao_hong = Girl.new(小红)

xiao_ming = Pursuit.new(xiao_hong)
xiao_ming.give_dolls
xiao_ming.give_flowers
xiao_ming.give_chocolate

只有代理的代码:

# -*- encoding: utf-8 -*-

#代理类
class Proxy
    attr_accessor :mm
    
    def initialize(mm)
        @mm = mm
    end
    
    def give_dolls
        puts "#{mm.name} 送你洋娃娃"
    end
    
    def give_flowers
        puts "#{mm.name} 送你鲜花"
    end
    
    def give_chocolate
        puts "#{mm.name} 送你巧克力"
    end

end

#被追求者类
class Girl
    attr_accessor :name
    
    def initialize(name)
        @name = name
    end
end

xiao_hong = Girl.new(小红)

xiao_ming = Proxy.new(xiao_hong)
xiao_ming.give_dolls
xiao_ming.give_flowers
xiao_ming.give_chocolate

只是把追求者类换成了代理类。

实际的代理模式代码:

# -*- encoding: utf-8 -*-

#公共接口module
module GiveGift
    def give_dolls
    end
    
    def give_flowers
    end
    
    def give_chocolate
    end
end

#追求者类
class Pursuit
    include GiveGift
    attr_accessor :mm, :name
    
    def initialize(mm)
        @mm = mm
    end
    
    def give_dolls
        puts "#{mm.name} 替#{name}送你洋娃娃"
    end
    
    def give_flowers
        puts "#{mm.name} 替#{name}送你鲜花"
    end
    
    def give_chocolate
        puts "#{mm.name} 替#{name}送你巧克力"
    end

end

#代理类
class Proxy
    include GiveGift
    attr_accessor :gg
    
    def initialize(mm)
        @gg = Pursuit.new(mm)
    end
    
    def give_dolls
        gg.give_dolls
    end
    
    def give_flowers
        gg.give_flowers
    end
    
    def give_chocolate
        gg.give_chocolate
    end

end

#被追求者类
class Girl
    attr_accessor :name
    
    def initialize(name)
        @name = name
    end
end

xiao_hong = Girl.new(小红)

xiao_ming = Proxy.new(xiao_hong)
xiao_ming.gg.name = 小明
xiao_ming.give_dolls
xiao_ming.give_flowers
xiao_ming.give_chocolate

 

代理模式:为其他对象提供一种代理以控制对这个对象的访问。

应用场景:

  • 远程代理

为一个对象在不同的地址提供局部代表,这样就可以隐藏一个对象存在于不同地址空间的事实。

  • 虚拟代理

是根据需要创建开销很大的对象。通过它来存放实例化需要很长时间的真实对象。

  • 安全代理

用来控制真是对象访问时的权限。

  • 智能代理

当调用真实对象时,代理处理另外一些事。

《大话设计模式》ruby版代码:代理模式

标签:

原文地址:http://www.cnblogs.com/fanxiaopeng/p/4198689.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!