Skip to content

Commit 1733fa3

Browse files
authored
Merge pull request #4935 from blackriper/main
Reto#29-kotlin
2 parents 3227870 + d696ef2 commit 1733fa3

File tree

2 files changed

+377
-0
lines changed

2 files changed

+377
-0
lines changed
Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
/*
2+
Interface Segregation Principle
3+
4+
Este principio nos dice que una clase nunca debe extender de interfaces con métodos que no usa,
5+
por el principio de segregación de interfaces busca que las interfaces sean lo más pequeñas
6+
y específicas posible de modo que cada clase solo implemente los métodos que necesita.
7+
8+
errores comunes con este principio
9+
10+
- Estaremos violando este principio si Tenemos clases que implementan métodos de interfaces que no se usan.
11+
12+
- Definimos interfaces con parámetros que no se van a utilizar en todas las clases
13+
14+
-cuando tenemos interfaces muy grandes y métodos que no son genéricos y que otras clases que implementen esta interfaz no puedan usar
15+
16+
*/
17+
18+
//ejemplo de lo que no debe de hacerce
19+
20+
21+
interface Bank {
22+
fun deposit(amount: Double)
23+
fun withdraw(amount: Double)
24+
fun getBalance()
25+
}
26+
27+
class AccountNormal(private var balance: Double):Bank{
28+
override fun deposit(amount: Double) {
29+
balance+=amount
30+
}
31+
32+
override fun withdraw(amount: Double) {
33+
balance-=amount
34+
}
35+
36+
override fun getBalance() {
37+
println("the balance is $balance")
38+
}
39+
40+
}
41+
// esta cuenta solo es de imversion y esta no pueda hacer retiros por lo tanto rompe este principio
42+
// porque solo retornamos el error
43+
class InterestAccount(private var balance: Double):Bank {
44+
override fun deposit(amount: Double) {
45+
balance += amount
46+
}
47+
48+
override fun withdraw(amount: Double) {
49+
throw Exception("not allowed this operation")
50+
}
51+
52+
override fun getBalance() {
53+
println("the balance is $balance")
54+
}
55+
}
56+
57+
// lo que debe de hacerce
58+
59+
// quitamos el metodo que solo se permite en las dos clases
60+
interface LspBank{
61+
fun deposit(amount: Double)
62+
fun getBalance()
63+
}
64+
//las inferfaces pueden extender de otras interfaces ahora este inferfaz hija herera los metodos del padre
65+
// pero agrega la fucnionalidad de withdraw
66+
interface LspNormalBank : LspBank{
67+
fun withdraw(amount: Double)
68+
}
69+
70+
class NormalAccountLsp(private var balance: Double):LspNormalBank {
71+
override fun withdraw(amount: Double) {
72+
balance -= amount
73+
}
74+
75+
override fun deposit(amount: Double) {
76+
balance += amount
77+
}
78+
79+
override fun getBalance() {
80+
println("the balance is $balance")
81+
}
82+
}
83+
84+
class InterestAccountLsp(private var balance: Double):LspBank {
85+
override fun deposit(amount: Double) {
86+
balance += amount
87+
}
88+
89+
override fun getBalance() {
90+
println("the balance is $balance")
91+
}
92+
}
93+
94+
fun exmapleLsp(){
95+
val normal = NormalAccountLsp(100.0)
96+
normal.deposit(100.0)
97+
normal.getBalance()
98+
normal.withdraw(50.0)
99+
normal.getBalance()
100+
101+
val inv = InterestAccountLsp(100.0)
102+
inv.deposit(100.0)
103+
inv.getBalance()
104+
105+
println("violation this principle")
106+
// clase que viola esta principio
107+
val interest = InterestAccount(100.0)
108+
interest.deposit(100.0)
109+
interest.getBalance()
110+
// me veo forzado a chacar el error
111+
runCatching { interest.withdraw(50.0)}.let { println(it.exceptionOrNull()?.message) }
112+
interest.getBalance()
113+
}
114+
115+
//ejercicio extra
116+
117+
enum class ColorPrint{
118+
BLACK_AND_WHITE,
119+
COLOR
120+
}
121+
122+
interface Printer{
123+
fun print(document:String)
124+
}
125+
126+
// aplicando el principio de ISP para crear una nueva interfaz cuando esta tenga multiples funciones
127+
interface MultiFunctionPrinter : Printer{
128+
fun sendFax(document:String):Boolean
129+
fun scan(document:String)
130+
}
131+
132+
class NormalPrinter(val color:ColorPrint):Printer{
133+
override fun print(document: String) {
134+
println("Printing $document in color: $color")
135+
}
136+
137+
}
138+
139+
class MultiFuncPrinter(val color:ColorPrint):MultiFunctionPrinter {
140+
override fun sendFax(document: String): Boolean {
141+
if (document.isNotEmpty()){
142+
println("Sending $document by fax")
143+
return true
144+
}
145+
return false
146+
}
147+
148+
override fun scan(document: String) {
149+
document.isNotEmpty().run {
150+
println("Scanning $document")
151+
}
152+
}
153+
154+
override fun print(document: String) {
155+
println("Printing $document in color: $color")
156+
}
157+
}
158+
159+
fun pritingDocument(printer:Printer, document:String){
160+
printer.print(document)
161+
}
162+
163+
fun examplePrinter(){
164+
val normalPrinter = NormalPrinter(ColorPrint.BLACK_AND_WHITE)
165+
pritingDocument(normalPrinter,"Hello World")
166+
val multiFuncPrinter = MultiFuncPrinter(ColorPrint.COLOR)
167+
pritingDocument(multiFuncPrinter,"Kotlin is son of Java")
168+
multiFuncPrinter.sendFax("Hello Comunity")
169+
multiFuncPrinter.scan("Hello World")
170+
}
171+
172+
173+
fun main() {
174+
exmapleLsp()
175+
examplePrinter()
176+
}
Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
/*
2+
Interface Segregation Principle
3+
4+
Este principio nos dice que una clase nunca debe extender de interfaces con métodos que no usa,
5+
por el principio de segregación de interfaces busca que las interfaces sean lo más pequeñas
6+
y específicas posible de modo que cada clase solo implemente los métodos que necesita.
7+
8+
errores comunes con este principio
9+
10+
- Estaremos violando este principio si Tenemos clases que implementan métodos de interfaces que no se usan.
11+
12+
- Definimos interfaces con parámetros que no se van a utilizar en todas las clases
13+
14+
-cuando tenemos interfaces muy grandes y métodos que no son genéricos y que otras clases que implementen esta interfaz no puedan usar
15+
16+
*/
17+
18+
//ejemplo de lo que no debe de hacerce
19+
20+
protocol Animal{
21+
func eat()
22+
func sleep()
23+
func run() throws->Void
24+
}
25+
26+
enum ErrorAnimal:Error{
27+
case IcannotRun(name:String)
28+
}
29+
30+
class Chicken:Animal{
31+
let name:String
32+
init(namePet:String){
33+
name=namePet
34+
}
35+
36+
func eat(){
37+
print("\(name) is eating")
38+
}
39+
40+
func sleep(){
41+
print("the chicken \(name) is sleeping")
42+
}
43+
44+
func run() throws->Void{
45+
print("the chicken \(name) is running")
46+
}
47+
}
48+
49+
// como el pez no puede correr mandamos un error por lo cual violamos este principio
50+
51+
52+
class Fish:Animal{
53+
let name:String
54+
init(namePet:String){
55+
name=namePet
56+
}
57+
58+
func eat(){
59+
print("\(name) is eating")
60+
}
61+
62+
func sleep(){
63+
print("the fish \(name) is sleeping")
64+
}
65+
66+
func run() throws->Void{
67+
throw ErrorAnimal.IcannotRun(name: name)
68+
}
69+
}
70+
71+
72+
let chicken=Chicken(namePet:"triki")
73+
chicken.eat()
74+
chicken.sleep()
75+
try chicken.run()
76+
77+
let fish=Fish(namePet:"bandalo")
78+
fish.eat()
79+
fish.sleep()
80+
do{
81+
try fish.run()
82+
}catch ErrorAnimal.IcannotRun(let name) {
83+
print("the fish \(name) cannot run ")
84+
}
85+
86+
// la forma correcta de cumplir el principio
87+
88+
protocol Specie{
89+
func eat()
90+
func sleep()
91+
}
92+
93+
// como la gallina si puede correr creamos una interfaz derivada de la original
94+
protocol EarthSpecie:Specie{
95+
func run()
96+
}
97+
98+
// ahora las clases quedan de la siguiente manera
99+
100+
class ChickenISP:EarthSpecie{
101+
let name:String
102+
init(namePet:String){
103+
name=namePet
104+
}
105+
106+
func eat(){
107+
print("\(name) is eating")
108+
}
109+
110+
func sleep(){
111+
print("the chicken \(name) is sleeping")
112+
}
113+
114+
func run() {
115+
print("the chicken \(name) is running")
116+
}
117+
}
118+
119+
class FishISP:Specie{
120+
let name:String
121+
init(namePet:String){
122+
name=namePet
123+
}
124+
125+
func eat(){
126+
print("\(name) is eating")
127+
}
128+
129+
func sleep(){
130+
print("the fish \(name) is sleeping")
131+
}
132+
}
133+
134+
let chick=ChickenISP(namePet:"blanquita")
135+
chick.eat()
136+
chick.sleep()
137+
chick.run()
138+
139+
let fishing=FishISP(namePet:"guason")
140+
fishing.eat()
141+
fishing.sleep()
142+
143+
// ejercicio extra
144+
145+
enum Color{
146+
case black_and_white
147+
case color
148+
}
149+
150+
// creamos una interfaz base de la cual haremos uns interface derivada
151+
152+
protocol Printer{
153+
func print(_ document:String)->String
154+
}
155+
156+
157+
protocol MultiFunctionPrinter:Printer{
158+
func sendFax(_ fax:String)->String
159+
func scanDocument(_ document:String)->String
160+
}
161+
162+
163+
struct NormalPrinter:Printer{
164+
let colorPrint:Color
165+
166+
func print(_ document:String)->String{
167+
return "printing \(document) in \(colorPrint)"
168+
}
169+
}
170+
171+
172+
struct MultifunPrinter:MultiFunctionPrinter{
173+
let colorPrint:Color
174+
175+
func sendFax(_ fax:String)->String{
176+
return "sending fax \(fax)"
177+
}
178+
179+
func scanDocument(_ document:String)->String{
180+
return "scan \(document)"
181+
}
182+
183+
func print(_ document:String)->String{
184+
return "printing \(document) in \(colorPrint)"
185+
}
186+
}
187+
188+
func printingDocument(thermal:Printer,content:String){
189+
print(thermal.print(content))
190+
}
191+
192+
193+
194+
let printer=NormalPrinter(colorPrint:.black_and_white)
195+
let multi=MultifunPrinter(colorPrint:.color)
196+
197+
printingDocument(thermal:printer,content:"Swift is great")
198+
printingDocument(thermal:multi,content:"Swift is embebed")
199+
200+
print(multi.sendFax("critical fail in system"))
201+
print(multi.scanDocument("WWDC2024 photos"))

0 commit comments

Comments
 (0)