【发布时间】:2010-11-10 12:13:18
【问题描述】:
我想创建一个静态类或单例类,它在其构造函数中接受对另一个对象的引用。静态类已经出来了,但我想我可以创建一个在其构造函数中接受参数的单例。到目前为止,我还没有运气弄清楚或在谷歌上搜索语法。这可能吗?如果是这样,我该怎么做?
很抱歉在最初的帖子中没有示例,我写的很匆忙。我觉得我的答案已经在回复中,但这里有一些我想要做的澄清:
我想创建一个特定类型的单个实例(称为 Singleton),但该类型的单个实例需要保存对不同对象的引用。
例如,我可能想创建一个单例“状态”类,它拥有一个 StringBuilder 对象和一个可以调用的 Draw() 方法,以便将所述 StringBuilder 写入屏幕。 Draw() 方法需要了解我的 GraphcisDevice 才能进行绘制。 所以我想这样做:
public class Status
{
private static Status _instance;
private StringBuilder _messages;
private GraphicsDevice _gDevice;
private Status(string message, GraphicsDevice device)
{
_messages.Append(message);
_gDevice = device;
}
// The following isn't thread-safe
// This constructor part is what I'm trying to figure out
public static Status Instance // (GraphicsDevice device)
{
get
{
if (_instance == null)
{
_instance = new Status("Test Message!", device);
}
return _instance;
}
}
public void UpdateMessage
...
public void Draw()
{
// Draw my status to the screen, using _gDevice and _messages
}
}
在整个代码中,我检索了我的状态单例并调用它的 UpdateMessage() 方法。
private Status _status = Status.Instance; // + pass reference to GraphicsDevice
_status.UpdateMessage("Foo!");
然后,在我的主类中,我还检索单例,并绘制它:
_status.Draw();
是的,这意味着无论我在哪里检索单例,我都需要通过传入对 GraphicsDevice 的引用来这样做,以防这是我第一次实例化单例。而且我可以/将使用不同的方法来检索像我的 Singleton 类中的 GraphicsDevice 这样基本的东西,例如在其他地方注册一个服务并在 Status 类中获取该服务。这个例子非常做作 - 我试图弄清楚 something 这样的模式是否是可能的。
【问题讨论】:
-
添加了对我所问问题的更好解释。
标签: c# constructor singleton