しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

Swiftで学ぶデザインパターン23 (Interpreterパターン)

今回はInterpreterパターンについて書いていきます。

デザインパターンとは

デザインパターンとはソフトウェア開発の設計方法の事です。
オブジェクト指向における再利用のためのデザインパターン』という本が出典で、全部で23種類のパターンが紹介されています。

Interpreterパターンとは

簡単な言語を作る事のできるパターンです。
文字列を解析してそれを元に実行する時に等使います。

NSPredicateで文字列で条件式を書く時のような事を実現してくれます。

SwiftでのInterpreterパターンの実装方法

SwiftでのInterpreterパターンは下のように実装します。
まだ把握しきれていないのですが、このパターンでは文字列を分割・保持するContextContext内のTokenの1つ1つに対応するExpressionの2つが出てきます。

import UIKit

class Context {
    var tokens: [String?]
    var index = 0
    
    init(str: String) {
        tokens = split(str, maxSplit: Int(INT_MAX), allowEmptySlices: true, isSeparator: { $0 == " " }).map({ return $0 })
        tokens.append(nil)
    }
    
    func nextToken() -> String? {
        if currentToken() == nil { return nil }
        
        return tokens[index++]
    }
    
    func currentToken() -> String? {
        return tokens[index]
    }
}

class Expression {
    let token: String
    
    init(token: String) {
        self.token = token
    }
    
    func execute() {}
}

class TerminalExpression: Expression {
    override func execute() {
        NSLog("\(token)です")
    }
}

class NonterminalExpression: Expression {
    let tag = "!"
    var expressions = [Expression]()
    
    func parse(context: Context) {
        while context.currentToken() != nil {
            if (context.currentToken() == tag) {
                expressions.append(NonterminalExpression(token: context.currentToken()!))
            } else {
                expressions.append(TerminalExpression(token: context.currentToken()!))
            }
            context.nextToken()
        }
    }
    
    override func execute() {
        NSLog("START!!! ")
        for expression in expressions {
            expression.execute()
        }
    }
}

let context = Context(str: "! A B ! C")
let token = context.currentToken()
context.nextToken()
let expression = NonterminalExpression(token: token!)
expression.parse(context)
expression.execute()

オブジェクト指向における再利用のためのデザインパターン

オブジェクト指向における再利用のためのデザインパターン