首页 > 学院 > 开发设计 > 正文

Ruby使用设计模式中的代理模式与装饰模式的代码实例

2019-10-26 19:28:39
字体:
来源:转载
供稿:网友

代理模式

需求:

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

没有代理的代码:

# -*- 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} 送你巧克力" endend#被追求者类class Girl attr_accessor :name  def initialize(name)  @name = name endendxiao_hong = Girl.new('小红')xiao_ming = Pursuit.new(xiao_hong)xiao_ming.give_dollsxiao_ming.give_flowersxiao_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} 送你巧克力" endend#被追求者类class Girl attr_accessor :name  def initialize(name)  @name = name endendxiao_hong = Girl.new('小红')xiao_ming = Proxy.new(xiao_hong)xiao_ming.give_dollsxiao_ming.give_flowersxiao_ming.give_chocolate

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

实际的代理模式代码:

# -*- encoding: utf-8 -*-#公共接口modulemodule GiveGift def give_dolls end  def give_flowers end  def give_chocolate endend#追求者类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}送你巧克力" endend#代理类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 endend#被追求者类class Girl attr_accessor :name  def initialize(name)  @name = name endendxiao_hong = Girl.new('小红')xiao_ming = Proxy.new(xiao_hong)xiao_ming.gg.name = '小明'xiao_ming.give_dollsxiao_ming.give_flowersxiao_ming.give_chocolate


装饰模式
 
需求:

给人搭配不同的服饰

代码版本一

# -*- encoding: utf-8 -*-class Person attr_accessor :name  def initialize(name)  @name = name end  def wear_t_shirts  puts '大T恤' end  def wear_big_trouser  puts '垮裤' end  def wear_sneakers  puts '破球鞋' end  def wear_suit  puts '西装' end  def wear_tie  puts '领带' end  def wear_leather_shoes  puts '皮鞋' end  def show  puts "*****装扮的#{name}/n/n" endendxc=Person.new('小菜')puts "******第一种装扮"xc.wear_t_shirtsxc.wear_big_trouserxc.wear_sneakersxc.showputs "******第二种装扮"xc.wear_suitxc.wear_tiexc.wear_leather_shoesxc.show            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表