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
好处:用户不需要了解各种股票,只需购买卖出基金即可。
Ruby中任务构建工具rake的入门学习教程
Rake简介Rake的意思是RubyMake,一个用ruby开发的代码构建工具.但是,为什么Ruby需要Rake按理说Ruby代码无需编译,应该不需要Rake才对呀原来,Rake另有妙用,即把Rake
Ruby程序中发送基于HTTP协议的请求的简单示例
1.建立HTTP连接(通过GET方式发送请求参数)require"open-uri"#如果有GET请求参数直接写在URI地址中uri='http://uri'html_response=nilopen(uri)do|http|html_response=http.readendputsh
Ruby的字符串与数组求最大值的相关问题讨论
max方法b=[1,3,55,777,2,4,6,8,0]对于数值型的数据,max会得到数组的最大值,min得到数组的最小值b.max=777b.min=0而对于字符串型数组比较大小没有实际意义,ruby
