it编程 > 前端脚本 > Ruby

Ruby设计模式编程中对外观模式的应用实例分析

71人参与 2024-05-19 Ruby

何为外观模式?

    外观模式为子系统中一组不同的接口提供统一的接口。外观定义了上层接口,通过降低复杂度和隐藏子系统间的通信以及依存关系,让子系统更加易于使用。

    比方说子系统中有一组不同的类,其中一些彼此依赖。这让客户端难以使用子系统中的类,因为客户端需要知道每一个类。外观起到整个子系统的入口。有些客户端只需要子系统的某些基本行为,而对子系统的类不做太多定制,外观为这样的客户端提供简化的接口。只有需要从某些子系统的类定制更多行为的客户端,才会关注外观背后的细节。

    外观模式:为系统中的一组接口提供一个统一的接口。外观定义一个高层接口,让子系统更易于使用。

何时使用外观模式?

ruby版外观模式应用
需求:

股民买卖股票

初步代码:

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

#股票1
class stock1
  def buy
    puts '股票1买入'
  end
  
  def sell
    puts '股票1卖出'
  end
end

#股票2
class stock2
  def buy
    puts '股票2买入'
  end
  
  def sell
    puts '股票2卖出'
  end
end

#股票3
class stock3
  def buy
    puts '股票3买入'
  end
  
  def sell
    puts '股票3卖出'
  end
end

#国债1
class nationaldebt1
  def buy
    puts '国债1买入'
  end
  
  def sell
    puts '国债1卖出'
  end
end

#房地产1
class realty1
  def buy
    puts '房地产1买入'
  end
  
  def sell
    puts '房地产1卖出'
  end
end
s1 = stock1.new
s2 = stock2.new
s3 = stock3.new
n1 = nationaldebt1.new
r1 = realty1.new

s1.buy
s2.buy
s3.buy
n1.buy
r1.buy

s1.sell
s2.sell
s3.sell
n1.sell
r1.sell

问题:

可以发现用户需要了解股票、国债、房产情况,需要参与这些项目的具体买和卖,耦合性很高。

改进代码

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

#股票1
class stock1
  def buy
    puts '股票1买入'
  end
  
  def sell
    puts '股票1卖出'
  end
end

#股票2
class stock2
  def buy
    puts '股票2买入'
  end
  
  def sell
    puts '股票2卖出'
  end
end

#股票3
class stock3
  def buy
    puts '股票3买入'
  end
  
  def sell
    puts '股票3卖出'
  end
end

#国债1
class nationaldebt1
  def buy
    puts '国债1买入'
  end
  
  def sell
    puts '国债1卖出'
  end
end

#房地产1
class realty1
  def buy
    puts '房地产1买入'
  end
  
  def sell
    puts '房地产1卖出'
  end
end

#基金类
class fund
  attr_accessor s1, s2, s3, n1, r1
  
  def initialize
    s1 = stock1.new
    s2 = stock2.new
    s3 = stock3.new
    n1 = nationaldebt1.new
    r1 = realty1.new
  end
  
  def buy
    s1.buy
    s2.buy
    s3.buy
    n1.buy
    r1.buy
  end
  
  def sell
    s1.sell
    s2.sell
    s3.sell
    n1.sell
    r1.sell
  end
end

f1 = fund.new
f1.buy
f1.sell

好处:用户不需要了解各种股票,只需购买卖出基金即可。

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

Ruby中任务构建工具rake的入门学习教程

05-19

详解组合模式的结构及其在Ruby设计模式编程中的运用

05-19

设计模式中的模板方法模式在Ruby中的应用实例两则

05-19

实例解析Ruby设计模式编程中Strategy策略模式的使用

05-19

实例讲解Ruby使用设计模式中的装饰器模式的方法

05-19

Ruby设计模式编程中使用Builder建造者模式的实例

05-19

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论