目前我对这种"设计模式"非常感兴趣.我不确定是否有使用这种严格的全局状态实施的垮台.那么,你认为什么时候不在应用程序中练习单身?
例如,每个人都知道如何为Singleton Design Pattern.say编写代码
public class Singleton
{
// Private static object can access only inside the Emp class.
private static Singleton instance;
// Private empty constructor to restrict end use to deny creating the object.
private Singleton()
{
}
// A public property to access outside of the class to create an object.
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
Run Code Online (Sandbox Code Playgroud)
很明显,当我们创建任何类的实例时,很多时候会为每个实例分配内存,但在Singleton设计模式的情况下,单个实例为所有调用提供服务.
1)我有点困惑,真的没有意识到原因是什么......当一个人应该选择Singleton Design Pattern时.只是为了节省一些记忆或任何其他好处.
2)假设任何单个程序可以有多个类,那么哪些类应遵循Singleton设计模式?Singleton …
你可以将实例命名为与构造函数名称相同吗?
var myFunc = new function myFunc(){};
Run Code Online (Sandbox Code Playgroud)
?
看起来,这将使用新实例替换Function对象...这意味着这是一个很好的Singleton.
我没有看到有人使用这个,所以我想,这有些缺点,我不知道...
有什么想法吗?
请考虑以下代码:
// This code safely publishes the Publishable object
public static Publishable publishable= new Publishable();
Run Code Online (Sandbox Code Playgroud)
我已经看到了这种发布自定义Publishable对象的方法,我读到这是安全的.我的问题是: