Swift Classes基本D.R.Y原则

时间:2017-07-30 00:27:41

标签: ios swift class

有一个名为Nike的类并创建该类的实例是我认为我应该做的以避免代码重复。这是最聪明的方法吗?

enum Condition {
    case poor
    case fair
    case excellent
}

class Shoe {

var color: Condition
var laces: Condition

init(color: Condition, laces: Condition) {
    self.color = color
    self.laces = laces
}

}

class Nikeone: Shoe {

var texture: Condition
var sole: Condition

 init(color: Condition, laces: Condition, texture: Condition, sole: Condition) {
  self.texture = texture
  self.sole = sole
super.init(color: color, laces: laces)
 }
}




class NikeTwo: Shoe {

var texture: Condition
var sole: Condition

init(color: Condition, laces: Condition, texture: Condition, sole: Condition) {
    self.texture = texture
    self.sole = sole
    super.init(color: color, laces: laces)
}

 }

class NikeThree: Shoe {

var texture: Condition
var sole: Condition

init(color: Condition, laces: Condition, texture: Condition, sole: Condition) {
    self.texture = texture
    self.sole = sole
    super.init(color: color, laces: laces)
}
}

有一个名为Nike的类并创建该类的实例是我认为我应该做的以避免代码重复。这是最聪明的方法吗?

1 个答案:

答案 0 :(得分:0)

您最好的方法是按照建议创建一个名为Shoe的基类。

enum Condition {
    case poor
    case fair
    case excellent
}

class Shoe {
    var color: Condition
    var laces: Condition

    init(color: Condition, laces: Condition) {
        self.color = color
        self.laces = laces
    }
}

然后,您将创建一个名为NikeShoe的子类:

class NikeShoe: Shoe {
    var texture: Condition
    var sole: Condition

    init(color: Condition, laces: Condition, texture: Condition, sole: Condition) {
        self.texture = texture
        self.sole = sole
        super.init(color: color, laces: laces)
    }
}

然后你会创建你想要的鞋子:

let shoeA = NikeShoe(…)
let shoeB = NikeShoe(…)