何为外观模式?
外观模式为子系统中一组不同的接口提供统一的接口。外观定义了上层接口,通过降低复杂度和隐藏子系统间的通信以及依存关系,让子系统更加易于使用。
比方说子系统中有一组不同的类,其中一些彼此依赖。这让客户端难以使用子系统中的类,因为客户端需要知道每一个类。外观起到整个子系统的入口。有些客户端只需要子系统的某些基本行为,而对子系统的类不做太多定制,外观为这样的客户端提供简化的接口。只有需要从某些子系统的类定制更多行为的客户端,才会关注外观背后的细节。
外观模式:为系统中的一组接口提供一个统一的接口。外观定义一个高层接口,让子系统更易于使用。
何时使用外观模式?
- 子系统正逐渐变得复杂。应用模式的过程中演化出许多类,可以使用外观为这些子系统提供一个较简单的接口。
- 可以使用外观对子系统进行分层。每个子系统级别有一个外观作为入口点。让它们通过其外观进行通信,可以简化它们的依赖关系。
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,设计模式,外观模式
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
内蒙古资源网 Copyright www.nmgbbs.com
暂无“Ruby设计模式编程中对外观模式的应用实例分析”评论...
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。