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

时间:2022-09-03 12:50:26

何为外观模式

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

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

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

何时使用外观模式?

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

Ruby版外观模式应用
需求:

股民买卖股票

初步代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# -*- 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

问题:

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

改进代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# -*- 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

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