介紹
Day2介紹了單例模式(Singleton pattern),其缺點為獲取單例的程式需知道該單例的具體(concrete),例如獲取單例時會寫:YearLogger* yearLogger = YearLogger::GetInstance();
這裡用戶程式碼需先知道具體的YearLogger類,此讓用戶程式碼與YearLogger類形成了耦合。
Game Programming Pattern一書對此提供了一種寫法,概念為把目標單例多加一層抽象,獲取該單例的程式不須知道該單例的具體,僅需用該抽象層來操作單例。
C++範例
#include <iostream>
#include <string>
class Logger
{
public:
virtual ~Logger() {}
virtual void Log() const = 0;
};
class YearLogger : public Logger
{
public:
virtual void Log() const
{
std::cout << "2023" << std::endl;
}
};
class Locator
{
public:
static void Provide(Logger *service)
{
m_logger = service;
}
static Logger *GetLogger()
{
return m_logger;
}
private:
static Logger *m_logger;
};
Logger* Locator::m_logger;
int main()
{
// 創建yearLogger實例
YearLogger *yearLogger = new YearLogger();
// 將yearLogger實例存入locator
Locator::Provide(yearLogger);
// 獲取logger實例
Logger *pLogger = Locator::GetLogger();
// 用logger印訊息
pLogger->Log();
delete yearLogger;
return 0;
}
Outpu:
2023
Ref:
https://gameprogrammingpatterns.com/service-locator.html