[概念] SRP 單一職責原則的問題

作者: stillboy (joey)   2017-08-22 11:47:32
小弟最近公司專案需要 開始接觸到設計模式
使用的語言是 Javascript 目前自己自修看了幾本書
覺得很受用 但面臨到自己的專案上 滿沒有頭緒的
有兩個問題想跟前輩們討論
(1)
假設我一個初始化函數叫做 init (),在沒有設計模式的情況下,code如下
class Player {
init () {
if(player) {
destroy(player)
} else {
player = new Player()
return player
}
}
簡單來說 如果player這個變數存在 就destory 沒有就為他創造一個實體
對於init而言,它做了
1. 判斷player是否有值
2. 創造一個player
3. destroy
所以以上的class就會變成
class Player {
init() { }
isPlayerExisted () { }
createPlayer () { }
destroy () { }
}
思考了一下 寫成
class Player {
init() {
if ( isPlayerExisted() ) {
destroy()
} else {
createPlayer ()
}
}
但感覺好像跟原本的沒什麼差別..只是實作被包起來了..
而這樣感覺init函數還是符合SRP原則嗎?
會這樣說的原因是 init 其實還是做了不只一個職責..
※ 編輯: stillboy (114.32.177.86), 08/22/2017 11:51:20

Links booklink

Contact Us: admin [ a t ] ucptt.com