## 30.工廠模式
想象一下一家餐館,它實際上是一家食品工廠。 如果你需要 dosa <sup class="footnote">[ [64](#_footnotedef_64 "View footnote.") ]</sup> ,請問服務員,如果你需要 idiyappam <sup class="footnote">[ [65](#_footnotedef_65 "View footnote.") ]</sup> ,請問服務員 它。 本質上,飯店或食品工廠創建了一個稱為服務員的通用界面,供你訂購任何東西。 你只問他,他就送了,你不必關心 dosa 的制作方式或 idiyappam 的制作方式。
在編程中,你可以做同樣的事情,你可以實現一個工廠類,該類隱藏了制造對象的困難,并為你提供了一個通用的接口來制造對象。 看下面的代碼 [factory.rb](code/design_patterns/factory.rb) 。 輸入并運行它。
```rb
```
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
```rb
|
```
# factory.rb
class Shape
def draw
puts "In instance of #{self.class}"
end
end
class Square < Shape
end
class Circle < Shape
end
class ShapeFactory
def get_shape type
case type
when :square then Square.new
when :circle then Circle.new
end
end
end
shape_factory = ShapeFactory.new
square = shape_factory.get_shape :square
circle = shape_factory.get_shape :circle
square.draw
circle.draw
```rb
|
```
輸出:
```rb
In instance of Square
In instance of Circle
```
讓我們看看它是如何工作的。 代碼中的重點是這一點
```rb
class ShapeFactory
def get_shape type
case type
when :square then Square.new
when :circle then Circle.new
end
end
end
```
我們有一個名為`ShapeFactory`的類,該類提供了通過函數`get_shape`制作對象的通用接口。 我們將要創建的對象類型傳遞給此`get_shape`。 由于這只是示例,此處的工廠模式看起來像是使代碼復雜而不是程序員更簡單,但是在現實生活中,對象的創建可能非常復雜,如果工廠類可以掩蓋復雜性,那么它的生命就可以了。 程序員使用它來構建他的軟件將變得簡單。
### 30.1。 行使
想象一下,你正在編寫用于游戲的軟件,并且需要創建敵對對象,例如坦克,直升機,導彈發射器,步兵等。 編寫一個工廠模式,當你調用`Enemy.random`時會返回一個隨機的敵人對象。
- 前言
- 紅寶石
- 先決條件
- 1.安裝 Ruby
- 2.在線資源
- 3.入門
- 4.比較與邏輯
- 5.循環
- 6.數組
- 7.哈希和符號
- 8.范圍
- 9.功能
- 10.可變范圍
- 11.類&對象
- 12.安全導航
- 13.打破大型程序
- 14.結構和 OpenStruct
- 15. Rdoc
- 16. Ruby 樣式指南
- 17.模塊和混入
- 18.日期和時間
- 19.文件
- 20. Proc,Lambda 和塊
- 21.多線程
- 22.異常處理
- 23.正則表達式
- 24.寶石
- 25.元編程
- 26.基準
- 27.測試驅動開發
- 28.觀察者模式
- 29.模板模式
- 30.工廠模式
- 31.裝飾圖案
- 32.適配器模式
- 33.單例模式
- 34.復合模式
- 35.建造者模式
- 36.策略模式
- 贊助商
- 捐
- 人們怎么說
- 版權
- 取得這本書