单身人士应该是可以继承的吗? [英] A Singleton should be inheritable or not?

查看:79
本文介绍了单身人士应该是可以继承的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



根据Gof的说法,当唯一的实例应该可以通过子类化来扩展,而客户端
应该能够使用扩展的实例而不修改它们的代码。



但是为什么我会看到密封和私有构造函数示例在 MSDN

解决方案

在我的项目中,我使用Mark Seemanns的书中的依赖注入.NET中的Ambient Context实现。这种模式的主要使用点是,当您要求当前实例时,始终会有某些东西,而且可以通过其他实现来切换上下文。
F.E。

  public class TimeContext 
{
private static TimeContext _

public static TimeContext当前
{
get
{
if(_instance == null)
{
_instance = new的DefaultContext();
}
return _instance;
}
set
{
if(value!= null)
{
_instance = value;
}
}
}
public abstract DateTime GetDateTime();
}

具体实现上下文应该像

  public class DefaultContext:TimeContext 
{
public DateTime GetDateTime()
{
returm DateTime.Now() ;
}

}



A Singleton should be inheritable or They should not be ?

According to Gof "when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code."

but then why do i see Sealed and Private constructor examples on MSDN

解决方案

In my projects I use an Ambient Context implementation from Mark Seemanns book Dependency Injection in .NET. The main point of use of that pattern is that always when you are asking for Current instance, there has to be something and also Context can be switched by other implementation. F.E.

public class TimeContext
{
    private static TimeContext _instance;

    public static TimeContext Current
    {
        get
        {
            if (_instance == null)
            {
                _instance = new DefaultContext();
            }
            return _instance;
        }
        set
        {
            if (value != null)
            {
                _instance = value;
            }
        }
    }
    public abstract DateTime GetDateTime();
}

and concrete implementation of context should be like

public class DefaultContext : TimeContext
{
    public DateTime GetDateTime()
    {
        returm DateTime.Now();
    }

}

这篇关于单身人士应该是可以继承的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆