C. Keith Ray

C. Keith Ray is developing software for Sizeography and Upstart Technology. He writes code for multiple platforms and languages, including iOS® and Macintosh®.
Go to Sizeography and Upstart Technology to join our mailing lists and see more about our products. Keith's Résumé (pdf)

Saturday, April 15, 2017

Template Design Pattern in Swift

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"

As you can see, Swift doesn't allow us to declare a method "abstract". It's similar to Objective-C and Smalltalk in this way. We can put in an assertion or throw an exception, but we don't have the compiler forcing us to override/implement the abstract method.

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