我如何在Swift中重写这个Objective-C策略模式?

时间:2014-07-30 05:16:45

标签: ios swift

我看到this example of the Strategy pattern in Objective-C,但我很好奇使用Swift设置相同的模式。

我如何在Swift中做这样的事情?

2 个答案:

答案 0 :(得分:2)

(十六个月后......)

drewag的答案很好并且工作得很好但是因为在Swift中,函数是一等公民,所以可以通过废除围绕策略定义的协议和类来简化答案。类别别名的使用是可选的,但有助于自我记录代码。

class Dog {
    var position: Int = 0
    var strategy: DogStrategy
    func updatePosition() {
        position = strategy(position)
    }
    init(strategy: DogStrategy) {
        self.strategy = strategy
    }
}

/// The strategy is implemented by any function that takes a position and returns another.
typealias Position = Int
typealias DogStrategy = (Position) -> Position

// Strategy one.
func slowDogStrategy(position: Position) -> Position {
    return position + 1;
}

// Strategy two,
func fastDogStrategy(position: Position) -> Position {
    return position + 5;
}

var fastDog = Dog(strategy: fastDogStrategy)
var slowDog = Dog(strategy: slowDogStrategy)

答案 1 :(得分:1)

您的链接示例几乎没有任何内容无法直接转换为Swift:

class Dog {
    var position: Int = 0
    var strategy: DogStrategy

    init(strategy: DogStrategy) {
        self.strategy = strategy
    }

    func updatePosition() {
        self.position = self.strategy.getNewPositionFromPosition(self.position)
    }
}

class DogStrategy {
    func getNewPositionFromPosition(position: Int) -> Int {
        return position + 2;
    }
}

虽然,我认为这更好地实现并作为协议进行说明(在Objective-C中也是如此):

protocol DogStrategy {
    func getNewPositionFromPosition(position: Int) -> Int
}

class Dog {
    var position: Int = 0
    var strategy: DogStrategy
    func updatePosition() {
        self.position = self.strategy.getNewPositionFromPosition(self.position)
    }
    init(strategy: DogStrategy) {
        self.strategy = strategy
    }
}

class SlowDogStrategy: DogStrategy {
    func getNewPositionFromPosition(position: Int) -> Int {
        return position + 1;
    }
}

class FastDogStrategy: DogStrategy {
    func getNewPositionFromPosition(position: Int) -> Int {
        return position + 5;
    }
}

var fastDog = Dog(strategy: FastDogStrategy())
var slowDog = Dog(strategy: SlowDogStrategy())