0. 應用場景
將用戶上傳到的圖片, 根據保密程度有三種處理方式,1.放置於服務器上,可直接訪問, 2.放置於服務器上,但需要從數據庫查詢路徑,3.將文件寫入MongoDB中
1. Nodejs操作思路
因為本人畢業先做的Nodejs后端開發, 一些思路固定了,習慣了之前的編程方法,再轉移到現用語言中。
function saveNormalFile() {
console.log("放置於服務器上,可直接訪問")
}
function savePathToDB() {
console.log("放置於服務器上,但需要從數據庫查詢路徑")
}
function saveFileToDB() {
console.log("將文件寫入MongoDB")
}
const methodMap = {
0:saveNormalFile,
1:savePathToDB,
2:saveFileToDB
};
const file = {
level:0,
data:"二進制流",
name:"2333.png",
user:"aha"
};
// 根據文件類型,選擇存儲函數
methodMap[file.level]();
程序輸出: 放置於服務器上,可直接訪問
switch case的時間復雜最壞情況為n, 平均為 (1+2+3+4+ . . . . . +n) / n = ( (1+n) * n/2 ) / n = (1+n)/ 2, 並且代碼的分支語句太多,不易維護
2. 雖然對C#不熟練,但是肯定可以解決,傳遞函數的方式就是指針,使用引用類型delegate,最終結果如下
class DictionaryDelegate
{
public delegate void Method(); // 我的函數沒有參數和返回, 可根據自己的需求修改
static Method saveNormalFile = () =>
{
Console.WriteLine("放置於服務器上,可直接訪問");
};
static Method savePathToDB = () =>
{
Console.WriteLine("放置於服務器上,但需要從數據庫查詢路徑");
};
static Method saveFileToDB = () =>
{
Console.WriteLine("將文件寫入MongoDB");
};
Dictionary<string, Method> MethodDictionary = new Dictionary<string, Method>
{
{"0", saveNormalFile},
{"1", savePathToDB},
{"2", saveFileToDB},
};
public DictionaryDelegate()
{
MethodDictionary["0"]();
}
}
3. 如果不使用簡單的lamda函數,也可正常調用委托函數
class DictionaryDelegate
{
public delegate void Method(); // 我的函數沒有參數和返回, 可根據自己的需求修改
public void saveNormalFile()
{
Console.WriteLine("放置於服務器上,可直接訪問");
}
public DictionaryDelegate()
{
Dictionary<string, Method> MethodDictionary = new Dictionary<string, Method>
{
{"0", new Method(saveNormalFile) }
};
MethodDictionary["0"].BeginInvoke(null, null);
}
}
