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

2023-12-05 0 583

何为外观模式

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

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

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

何时使用外观模式?

  • 子系统正逐渐变得复杂。应用模式的过程中演化出许多类,可以使用外观为这些子系统提供一个较简单的接口。
  • 可以使用外观对子系统进行分层。每个子系统级别有一个外观作为入口点。让它们通过其外观进行通信,可以简化它们的依赖关系。

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编程中的运用实例解析
  • 实例解析Ruby设计模式开发中对观察者模式的实现
  • 深入剖析Ruby设计模式编程中对命令模式的相关使用
  • 详解组合模式的结构及其在Ruby设计模式编程中的运用
  • 设计模式中的模板方法模式在Ruby中的应用实例两则
  • 实例解析Ruby设计模式编程中Strategy策略模式的使用
  • 实例讲解Ruby使用设计模式中的装饰器模式的方法
  • Ruby设计模式编程中使用Builder建造者模式的实例
  • 详解Ruby设计模式编程中对单例模式的运用
  • Ruby设计模式编程之适配器模式实战攻略
  • Ruby使用设计模式中的代理模式与装饰模式的代码实例
  • Ruby中使用设计模式中的简单工厂模式和工厂方法模式
  • 解析proxy代理模式在Ruby设计模式开发中的运用

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 Ruby Ruby设计模式编程中对外观模式的应用实例分析 https://www.u-9.cn/jiaoben/ruby/100820.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务