-
Notifications
You must be signed in to change notification settings - Fork 41
/
Contents.swift
123 lines (91 loc) · 2.54 KB
/
Contents.swift
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import Foundation
// Components:
// Adaptee
// Adapter
// Target
// Types:
// Extension adapter
// Class adapter
// Let's assume by some reasons our Lightning Socket protocol has no ability to be programmatically connected, just attached and it immediately stars charging
protocol LightningSocketType {
func attach()
func charge()
}
/// Adaptee that needs to be adapted to work with USB-C port
class iPhone: LightningSocketType {
var isLoggingEnabled: Bool = true
/// ...
/// Among other possbilities, our iPhone struct has an ability to charge our phone
///...
// MARK: - Conformance to LightningSocketType protocol
func attach() {
if isLoggingEnabled {
print("iPhone is being attached using Lightning Socket")
}
}
func charge() {
if isLoggingEnabled {
print("iPhone is being charged using Lightning Socket")
}
}
}
protocol USBCSocketType {
func connect()
func charge()
}
/// Adapter
class USBCAdapter: USBCSocketType {
// MARK: - Properties
var lightningSocket: LightningSocketType {
didSet {
disableLogging()
}
}
// MARK: - Initializers
init(for lightningSocket: LightningSocketType) {
self.lightningSocket = lightningSocket
disableLogging()
}
// MARK: - Methods
private func disableLogging() {
(self.lightningSocket as? iPhone)?.isLoggingEnabled = false
}
// MARK: - Conformance to USBCSocketType protocol
func connect() {
print("iPhone is being connected using USB-C Socket Adapter")
lightningSocket.attach()
}
func charge() {
print("iPhone is being charged using USB-C Socket Adapter")
lightningSocket.charge()
}
}
/// Target
class USBCCharger {
var socket: USBCSocketType {
didSet {
connect()
}
}
init(using socket: USBCSocketType) {
self.socket = socket
connect()
}
func charge() {
socket.charge()
}
private func connect() {
self.socket.connect()
}
}
//: Usage:
let phone = iPhone()
let usbcAdapter = USBCAdapter(for: phone)
let charger = USBCCharger(using: usbcAdapter)
charger.charge()
// Created new iPhone
let newiPhone = iPhone()
// Reused the old USB-C socket adapter in order to be able to connect to the USB-C charger
usbcAdapter.lightningSocket = newiPhone
// Reattached the adapter with a new iPhone device
charger.socket = usbcAdapter