本文介绍了单例类:静态属性还是非静态属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编程一个充当Singleton的Class。我想知道,这个类有非静态属性是否有意义?



伪代码示例:

  class Foo extends MySingletonClass {

private static string bar;
私人字符串baz;

/ *更多代码在这里* /

}


解决方案

静态属性没有错,但在单例中是多余的。



另外,如果你有静态属性,然后你需要将类更改为不再是单例,您将需要更改属性(作为访问它的每个代码)。所以我建议你不要标记为静态,除非真的需要。


I´m programming a Class which acts as a Singleton. I was wondering, does it make sense to have non-static properties for this class?

Pseudocode example:

class Foo extends MySingletonClass {

    private static string bar;
    private string baz;

    /* more code here */

}
解决方案

It's not wrong to have static properties, but it's redundant in a singleton.

Also, if you have static properties, and later you need to change the class to not be a singleton no more, you'll need to change the properties either (as every code that access it). So I recommend you not to mark as static, unless really needed.

这篇关于单例类:静态属性还是非静态属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:15