Skip to content

Instantly share code, notes, and snippets.

@LH17
Last active April 14, 2018 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LH17/950e39849055dc6dc8ca1178039323ba to your computer and use it in GitHub Desktop.
Save LH17/950e39849055dc6dc8ca1178039323ba to your computer and use it in GitHub Desktop.
// Protocol
protocol Fruit {
func getPrice() -> String
func getCount() -> Int
}
// Implements Fruit Protocol
class Orange: Fruit {
func getPrice() -> String {
return "$5"
}
func getCount() -> Int {
return 2
}
}
// Implements Fruit Protocol
class Banana: Fruit {
func getPrice() -> String {
return "$2"
}
func getCount() -> Int {
return 5
}
}
// Implements Fruit Protocol
class Grapes: Fruit {
func getPrice() -> String {
return "$3.5"
}
func getCount() -> Int {
return 1
}
}
// Fruit type enum
enum FruitType {
case orange, banana, grapes
}
// factory class with a static method
class FruitFactory {
// Returns the object ofthe class that implemnets Fruit protocol
static func getFruit(forType type: FruitType) -> Fruit? {
switch type {
case .orange:
return Orange()
case .banana:
return Banana()
case .grapes:
return Grapes()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment