我一直在研究封裝的概念,並發現了一些關於像this one和this one這樣的話題的體面線索。但是我一直無法找到我所具有的特定問題的答案。我將在Swift中使用一個示例。正確應用封裝
假設你有一個對象,它的類型是旅遊路徑的:
class RoadTrip() {
private var duration: Double
private var totalMiles: Double
private var gallonsOfFuel: Double
var averageMilesPerGallon: Double
}
現在讓我們假設該應用程序會計算averageMilesPerGallon
這是唯一的公共財產:
func calculateAverageMilePerGallon() -> Double {
let mpg = totalMiles/gallonsOfFuel
return mpg
}
如若計算每加侖平均英里數是RoadTrip對象的私有方法,該方法執行並更新其averageMilesPerGallon
,或者在單獨的工具類中通過另一方法執行計算,然後更新averageMilesPerGallon
RoadTrip對象的屬性是否使用了會設置值的增變量方法?
編輯:這是我的單個類,其中包含我的應用程序的基本計算。我走近它基於我在iTunes上斯坦福大學的過程中瞭解到這樣一來,但是我開始覺得我的情況下,我應該搬到這在很大程度上給我LiftEvent類:
infix operator ^^ { }
func ^^ (radix: Double, power: Double) -> Double {
return Double(pow(Double(radix), Double(power)))
}
class CalculatorBrain: NSObject {
var weightLifted: Double?
var repetitions: Double?
var oneRepMax: Double?
let dataManager = LiftEventDataManager()
func calculateOneRepMax(weightLifted: Double, repetitions: Int) -> Double {
let preferredFormulaID = UserDefaultsManager.sharedInstance.preferredFormula!
let formulas = dataManager.fetchSelectableFormulas()
let formulaName = formulas[preferredFormulaID].formulaName
switch formulaName {
case "Epley":
oneRepMax = weightLifted * (1 + Double(repetitions)/30.0)
return oneRepMax!
case "Baechle":
oneRepMax = weightLifted * (36/(37 - Double(repetitions)))
return oneRepMax!
case "Brzychi":
oneRepMax = weightLifted * (1 + (0.033 * Double(repetitions)))
return oneRepMax!
case "Lander":
oneRepMax = 100 * weightLifted/(101.3 - (2.67123 * Double(repetitions)))
return oneRepMax!
case "Lombardi":
oneRepMax = weightLifted * (Double(repetitions) ^^ 0.10)
return oneRepMax!
case "Mayhew":
oneRepMax = 100 * weightLifted/(52.2 + (41.9 * (2.71828 ^^ (-0.055 * Double(repetitions)))))
return oneRepMax!
case "O'Conner":
oneRepMax = weightLifted * (1 + 0.025 * Double(repetitions))
return oneRepMax!
default:
return 0.0
}
}
private func calculatePercentOfWeight(maxWeight: Double, percent: Double) -> Double {
return maxWeight * percent
}
func calculateWeightPercentages(maxWeight: String) -> [Int: Double] {
let weightPercentages = [1.0, 0.95, 0.90, 0.85, 0.80, 0.75, 0.70, 0.65, 0.60, 0.55, 0.50, 0.45, 0.40, 0.35, 0.30, 0.25]
var percentages = [Int: Double]()
for percent in weightPercentages {
let integerPercent = Int(percent * 100)
percentages[integerPercent] = calculatePercentOfWeight(Double(maxWeight)!, percent: percent)
}
return percentages
}
func convertBetweenUnits(fromUnit: Int, toUnit: Int, value: Double) -> Double {
let units = dataManager.fetchUnits()
let from = units[fromUnit].conversionRatio as Double
let to = units[toUnit].conversionRatio as Double
let result = Double(value * to/from)
return result
}
}
這聽上去像一個實用的解決方案具有任意的實用工具類,包含這樣的基本功能 – Alexander
你知道你的類沒有編譯,對嗎? – Alexander
與「封裝」無關嗎?與「變異者」無關? – matt