In the Template Design pattern, you write an abstract class where an algorithm is implemented, but at least one part of the algorithm is not implemented -- it calls an abstract/unimplemented method for some part of the algorithm. The subclass inherits from the abstract class, implementing the abstract method(s) but not changing the overall algorithm.
I will show two ways to implement this design pattern.
First, using classes:
import Foundation
class TemplateClass { // "Abstract" class
func doit() {
before()
during()
after()
}
func before() {
print("before")
}
func during() { // in C++ should be "pure virtual".
fatalError("subclass must override")
} // in Java, should be "abstract"
func after() {
print("after")
}
}
class TemplateClassExample: TemplateClass {
override func during() {
print("during")
}
}
var tx = TemplateClassExample()
tx.doit() // prints "before", "during", "after"
Second, using Protocols:
protocol TemplateProtocol {
func during()
}
extension TemplateProtocol {
func doit() {
before()
during()
after()
}
func before() {
print("before")
}
func after() {
print("after")
}
}
class TemplateProtocolExample: TemplateProtocol {
internal func during() {
print("during")
}
}
var tp = TemplateProtocolExample()
tp.doit() // prints "before", "during", "after"
Here the protocol forces us to implement the abstract method, but we can't put the algorithm's concrete methods in the protocol declaration, they have to go in the protocol extension. This seems to be a rather arbitrary restriction, but it's probably reflecting the way Swift evolved. I don't think the earliest versions of Swift allowed extending protocols with extensions containing concrete methods, though obviously Swift 3.x does allow this.
No comments:
Post a Comment