Skip to content

Commit 2ef36bc

Browse files
authored
Merge pull request #4110 from blackriper/main
Reto#23-swift
2 parents abef819 + ce00d68 commit 2ef36bc

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import Foundation
2+
3+
/*
4+
El patron singleton es un patron de diseño creacional que nos permite garantizar la unica instancia de una clase.
5+
para implementar este patron la clase o estructura debe cumplir los siguientes requisitos:
6+
7+
1. Debe tener un constructor privado
8+
2. Debe tener un metodo de inicializacion estatico que devuelva una instancia de la clase
9+
10+
para mas informacion puedes checar mi solucion en kotlin o visitar https://refactoring.guru/es/design-patterns/singleton
11+
12+
*/
13+
14+
class IngredientSinglenton {
15+
private var ingredients: [String] = []
16+
static let shared = IngredientSinglenton()
17+
private init() {}
18+
19+
func add(ingredient: String) {
20+
ingredients.append(ingredient)
21+
}
22+
23+
func showIngredients() {
24+
print(ingredients)
25+
}
26+
}
27+
28+
// aunque creamos dos instancias diferentes siguen utilizando la misma instancia de la clase IngredientSinglenton
29+
30+
let singleton = IngredientSinglenton.shared
31+
singleton.add(ingredient: "onions")
32+
singleton.showIngredients()
33+
34+
let singleton2 = IngredientSinglenton.shared
35+
singleton2.add(ingredient: "chicken")
36+
singleton2.showIngredients()
37+
38+
39+
// ejercicio extra
40+
41+
struct User{
42+
let id : UUID
43+
let username : String
44+
let name : String
45+
let email : String
46+
}
47+
48+
let mockDatabase = [
49+
User(id: UUID(), username: "blackriper", name: "Rodolfo", email: "[email protected]"),
50+
User(id: UUID(), username: "janedoe", name: "Jane", email: "[email protected]")
51+
]
52+
53+
enum MockError: Error {
54+
case userNotFound
55+
}
56+
57+
58+
59+
class SessionSingleton {
60+
static let shared = SessionSingleton()
61+
var currentSessionUser : User?
62+
63+
private init() {}
64+
65+
func login(username: String) throws {
66+
if let user = mockDatabase.first(where: {$0.username == username}) {
67+
currentSessionUser = user
68+
print("logged in with session user: \(currentSessionUser!)")
69+
}
70+
}
71+
72+
func logout() {
73+
currentSessionUser = nil
74+
print("logged out session user")
75+
}
76+
}
77+
78+
do {
79+
let session = SessionSingleton.shared
80+
try session.login(username: "blackriper")
81+
session.logout()
82+
83+
try session.login(username: "janedoe")
84+
session.logout()
85+
86+
} catch MockError.userNotFound {
87+
print("user not registered")
88+
}

0 commit comments

Comments
 (0)