我正在编写一个C#程序,用于记录和处理Microsoft Kinect的视频。我创建了一个KinectManager
类来检查传感器的状态,并执行诸如激活,停用和记录颜色流之类的操作。
由于只能插入一个Kinect传感器,因此每次运行程序时,我只需要一个KinectManager
类的实例。在这种情况下,将类或其方法设为静态是一种好习惯吗?
答案 0 :(得分:2)
虽然静态方法可能很方便,但请记住静态不是面向对象的设计。例如。继承不起作用,静态类不能实现接口。
此外,您可以获得更多耦合代码,因为替换静态调用比传递另一个实例更有效。
静态方法在不处理状态时更好(例如ToUpperCase(string)
) - 正如@Wazner所提到的那样。
在这种情况下,您可以使用Singleton pattern,这将确保只有一个实例。
例如:
public class KinectManager {
// instance, another option is to make it lazy, but be aware if it's needs to be threadsafe.
private static KinectManager _instance = new KinectManager();
//private ctor to ensure it won't be created outside this class .
private KinectManager () {}
// The instance
public static KinectManager Instance {
get { return _instance ;}
}
}
但请注意singleton pattern is overused in the real world。如果有两个实例出现问题,那么单例是确保不会发生这种情况的好方法。但是如果两个实例都没问题,那么单例模式可能会过度设计。