|
| 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) |
0 commit comments