Sometimes I find it useful to have a single class with multiple instances (configured differently via their properties), rather than multiple classes (inheritance).
??? Pattern
- Single class (Fruit)
- Different fruit are instances of Fruit, with properties configured correctly.
- Behavior implemented as blocks.
class Fruit {
var name: String
var color: UIColor
var averageWeight: Double
var eat: () -> ()
}
class FruitFactory {
static func apple() -> Fruit {
let fruit = Fruit()
fruit.name = "Apple"
fruit.color = UIColor.redColor()
fruit.averageWeight = 50
fruit.eat = {
washFruit(fruit)
takeBite(fruit)
}
return fruit
}
static func orange() -> Fruit {
let fruit = Fruit()
fruit.name = "Orange"
fruit.color = UIColor.orangeColor()
fruit.averageWeight = 70
fruit.eat = {
peelFruit(fruit)
takeBite(fruit)
}
return fruit
}
}
Inheritance Pattern
For reference, the same could have been implemented using inheritance:
- Multiple classes (Fruit, Apple, Orange)
- Different fruit are classes that inherit from
Fruit
. - Behavior implemented using standard methods that are overridden in subclasses.
class Fruit {
var name: String
var color: UIColor
var averageWeight: Double
func eat() {
// abstract method
}
}
class Apple: Fruit {
var name = "Apple"
var color = UIColor.redColor()
var averageWeight = 50
override func eat() {
washFruit(self)
takeBite(self)
}
}
class Orange: Fruit {
var name = "Orange"
var color = UIColor.orangeColor()
var averageWeight = 70
override func eat() {
peelFruit(self)
takeBite(self)
}
}
class FruitFactory {
static func apple() -> Fruit {
return Apple()
}
static func orange() -> Fruit {
return Orange()
}
}
What is the first pattern called?
Are there any resources to help me decide when to use one of these patterns over the other?
Off the top of my head, I can think of at least one reason to prefer inheritance:
- Imagine we need to add a new property to Apple, but not to Orange (e.g.
averageCoreWeight
). If you use inheritance this is trivial. If you use the first pattern, you will be left with a property that is only sometimes used.