《大话设计模式》ruby版代码:外观模式
2024-09-15 17:04:08
需求:
股民买卖股票
初步代码:
# -*- 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
好处:用户不需要了解各种股票,只需购买卖出基金即可。
外观模式:
为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
最新文章
- JavaScript中数组去除重复
- 异步post请求之代理方法
- 20145211 《Java程序设计》第6周学习总结——三笑徒然当一痴
- /bin/bash^M: bad interpreter: 没有那个文件或目录
- Thread与Runable
- hdu2545 树上战争 (并查集)
- JavaScript中,按值传递与按地址(引用)传递。
- @Index用法——javax.persistence.Index
- 解决secureCRT数据库里没有找到防火墙 '无'问题,转自:http://jingyan.baidu.com/article/9989c74601274bf649ecfe74.html
- wampserver 2.2装好后80端口未被占用,却打不开localhost
- Oracle EBS-SQL (SYS-5):sys_配置文件查询.sql
- easyui dataBox 增加一天,减少一天
- Selenium 学习笔记(一)
- C# 中使用面向切面编程(AOP)中实践代码整洁
- Vue使用watch监听一个对象中的属性
- sklearn导入模块问题:python ImportError: No module named datasets
- Python 实例方法
- Java使用HttpClient上传文件
- Vue上传文件:ElementUI中的upload实现
- JavaScript 那些不经意间发生的数据类型自动转换
热门文章
- 7 -- Spring的基本用法 -- 5... Spring容器中的Bean;容器中Bean的作用域;配置依赖;
- 如何才能知道外线是FSK还是DTMF制式?
- iOS中UIImage转换为NSData 方法
- Linux获取当前目录名,shell获取当前目录名
- 【Node.js】Mac 下安装node图文详解
- MQTT-SN协议乱翻之实现要点
- 浅析HTTPS与SSL原理
- luogu P2066 机器分配[背包dp+方案输出]
- 分布式数据库主键id生成策略
- 爬虫实战【3】Python-如何将html转化为pdf(PdfKit)