你好我正在尋找一些指導,以選擇一個編程設計模式,以適應我當前的項目。哪種編程設計模式適合這個項目?
我一直在努力尋找一個好的項目,開始正確使用模式,我剛開始的一個小項目似乎提供了一個完美的平臺來學習。
基本上我正在創建一個Telegram Bot來響應用戶的命令。這不是我遇到問題的部分,它是如何最好地構建我的代碼,以便添加新的命令是乾淨的和結構良好的。
我不需要任何人爲我編寫任何代碼,但是有沒有我可以實現的適合的設計模式?
這裏就是我目前在做puesudo(順便說一句,我使用Laravel)代碼:
//routes.php
Route::post('inbound', ['uses' => '[email protected]']);
//inboundController.php
public function marshall($inboundMessage){
//Extract the command from the inbound message eg "start"
$command = extractfromtext($text);
//Get the user id from the person who sent the message
$userID = extractIdfromtext($text);
//Compare the command in a switch statement
switch ($command){
case (start):
return $result = new commandStart($userID)->fire();
break;
case (demo):
return $result = new commandDemo($userID)->fire();
break;
case (another):
return $result = new commandAnother($userID)->fire();
break;
default:
break;
}
}
//Each command has it's own class:
//Class commandStart
public function __construct($userID){
$this->userID = $userID
}
publin fuction fire(){
//send a picture to the userID
}
//Class commandDemo
public function __construct($userID){
$this->userID = $userID
}
publin fuction fire(){
//send a message to the userID
}
//Class commandAnother
public function __construct($userID){
$this->userID = $userID
}
publin fuction fire(){
//send a video to the userID
}
這工作得很好,但我覺得
- 我重複了很多代碼(壞)
- 添加新命令意味着連續編輯「入站類」文件。我認爲這打破了SOLID中的開放式封閉原則。
- switch語句給我一個「代碼味道」。
我對所有不同類型的模式的名稱感到非常困惑。有人會建議我,哪一個適合這種情況?我很高興去研究它,以及它是如何實施的,但是我不想因爲我不知道更好而去追逐一個不合適的鵝。
謝謝。
編輯:它似乎在我的嘗試,使這個問題泛型我做得太鈍了。我已經在使用Larvel的MVC。這不是問題我認爲 - 我想知道哪種設計模式可以讓我輕鬆乾淨地添加更多命令 - 希望不必使用switch語句。
在閱讀了一些回覆之後,我想我開始明白該怎麼做。出於興趣 - 下面是建議的實際設計模式還是結構良好的代碼?
你試過MVC(模型 - 視圖 - 控制器)模型嗎? – odedta
使用function_exists()和class_exists(),這樣添加新命令只需要一個帶有fire方法的新類。他們都可以擴展一個抽象類,它可以定義你的共同構造函數並強制孩子實施火法 –
對不起,我不能幫你laravel,我不熟悉它。它被稱爲[抽象工廠設計模式]的設計模式(https://www.google.ro/?gws_rd=cr,ssl&ei=8GurVZWPOcSwsAGjsJS4CA#q=php+abstract+factory+design+pattern) –