Skip to content

Commit c6cd84c

Browse files
author
Sebastian Boldt
committed
added flyweight pattern
1 parent 8839355 commit c6cd84c

File tree

4 files changed

+79
-3
lines changed

4 files changed

+79
-3
lines changed

GOFSwift.xcworkspace/contents.xcworkspacedata

+2-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
* ✅ Decorator
3434
* ✅ Composite
3535
* ✅ Adapter
36+
* ✅ Flyweight
3637
* ❌ Facade
37-
* ❌ Flyweight
3838
* ❌ Protection Proxy
3939
* ❌ Virtual Proxy
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
//: [Previous](@previous)
2+
3+
import Foundation
4+
5+
protocol Soldier {
6+
func render(from location: CGPoint, to newLocation: CGPoint)
7+
}
8+
9+
class Infantry: Soldier {
10+
private let modelData: Data
11+
12+
init(modelData: Data) {
13+
self.modelData = modelData
14+
}
15+
16+
func render(from location: CGPoint, to newLocation: CGPoint) {
17+
// Remove rendering from original location
18+
// Graphically render at new location
19+
}
20+
}
21+
22+
class SoldierClient {
23+
var currentLocation: CGPoint
24+
25+
let soldier: Soldier
26+
27+
init(currentLocation: CGPoint, soldier: Soldier) {
28+
self.currentLocation = currentLocation
29+
self.soldier = soldier
30+
}
31+
32+
func moveSoldier(to nextLocation: CGPoint) {
33+
soldier.render(from: currentLocation, to: nextLocation)
34+
currentLocation = nextLocation
35+
}
36+
}
37+
38+
class SoldierFactory {
39+
40+
enum SoldierType {
41+
case infantry
42+
}
43+
44+
private var availableSoldiers = [SoldierType: Soldier]()
45+
static let sharedInstance = SoldierFactory()
46+
47+
private init(){}
48+
49+
private func createSoldier(of type: SoldierType) -> Soldier {
50+
switch type {
51+
case .infantry:
52+
let infantry = Infantry(modelData: Data())
53+
availableSoldiers[type] = infantry
54+
return infantry
55+
}
56+
}
57+
58+
func getSoldier(type: SoldierType) -> Soldier {
59+
if let soldier = availableSoldiers[type] {
60+
return soldier
61+
} else {
62+
let soldier = createSoldier(of: type)
63+
return soldier
64+
}
65+
}
66+
}
67+
68+
let soldierFactory = SoldierFactory.sharedInstance
69+
let infantry = soldierFactory.getSoldier(type: .infantry)
70+
let firstSoldier = SoldierClient(currentLocation: CGPoint.zero, soldier: infantry)
71+
let secondSoldier = SoldierClient(currentLocation: CGPoint(x: 5, y: 10), soldier: infantry)
72+
73+
firstSoldier.moveSoldier(to: CGPoint(x: 1, y: 5))
74+
75+
//: [Next](@next)

Structural.playground/contents.xcplayground

+1
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,6 @@
55
<page name='Decorator'/>
66
<page name='Composite'/>
77
<page name='Adapter'/>
8+
<page name='Flyweight'/>
89
</pages>
910
</playground>

0 commit comments

Comments
 (0)