上一篇文章中說(shuō)到的manager of managers,其中每個(gè)manager都是單例的實(shí)現(xiàn),當(dāng)然也可以使用靜態(tài)類實(shí)現(xiàn),但是相比于靜態(tài)類的實(shí)現(xiàn),單例的實(shí)現(xiàn)更為通用,可以適用大多數(shù)情況。如何設(shè)計(jì)這個(gè)單例的模板?
??先分析下需求,當(dāng)設(shè)計(jì)一個(gè)manager時(shí)候,我們希望整個(gè)程序只有一個(gè)該manager對(duì)象實(shí)例,一般馬上能想到的實(shí)現(xiàn)是這樣的:
public class XXXManager {
private static XXXManager instance = null;
private XXXManager {
// to do ...
}
public static XXXManager() {
if (instance == null)
{
instance = new XXXManager();
}
return instance;
}
}
如果一個(gè)游戲需要10個(gè)各種各樣的manager,那么以上這些代碼要復(fù)制粘貼好多遍。重復(fù)的代碼太多!!!想要把重復(fù)的代碼抽離出來(lái),怎么辦?答案是引入泛型。實(shí)現(xiàn)如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace QFramework {
public abstract class QSingleton<T> where T : QSingleton<T>
{
protected static T instance = null;
protected QSingleton()
{
}
public static T Instance()
{
if (instance == null)
{
// 如何new 一個(gè)T???
}
return instance;
}
}
}