静态方法用途
如果我有一个静态方法唯一的优点是我们只有一个副本。不需要有一个对象来调用该方法。创建对象也可以做同样的事情,即我们可以用对象调用方法。为什么我们应该有静态方法。有人可以举个例子来解释吗?
if i have a static method Only advantage is that we have single copy.Need not have a object to call the Method. The same can be done be creating an object i.e we can call method with object. Why should we have static method. Can someone provide a example to explain?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您有私有构造函数时,静态方法可能很有用,因为您想要抽象实例化过程。
例如在 C++ 中:
在该示例中,抽象只是调用了一个可访问的构造函数,但实际上您可能希望拥有一个共享的对象池,因此
create()
方法将管理这是给你的。有时,当您有需要在构造时初始化的 const 成员时,将其逻辑移至
private
静态方法中会更清晰,例如:Static methods can be useful when you have private constructors, because you want to abstract the instantiation process.
For example in C++:
In that example the abstraction just called an otherwise in accessible constructor, but in practice you might want to have a pool of objects which is shared and so the
create()
method would be managing this for you.Sometimes when you have const members which need to be initalised at construction time it can be cleaner to move the logic for this into a
private
static method, e.g.:当开发人员确实确定该方法在类中只有一个实例时,可以使用静态方法。没有其他实例可以改变这一点。
例如:
所以即使你创建了 people 对象的实例, getvalue 静态方法的返回也只产生 x + 3。
当您确实确定要创建数学或物理方法等函数方法时,通常会使用它。
您可以参考使用静态观点的函数式编程。
一些老派人士过度使用静态方法而不是采用 OOP 方法。
例如:
上面的实现可能有数千行。
这种风格随处可见,使其像 OOP 风格(因为它发生在类中),但像过程方法一样思考。
这是一个帮助,因为并不是所有人都理解 OOP 风格而不是喜欢 OOP 风格。
使用静态的另一个优点是节省内存占用并且速度更快。
您可以在博客中看到: http://www.dotnetperls.com/callvirt
The static method is used when developer is really sure the method is only have one instance in the class. There are no other instance that can change that.
eg :
So even you are make instances of object people, the return from getvalue static method only produce x + 3.
It is usually used when you are really sure to make a functional method like math or physics method.
You can refer to functional programming that using static point of view.
Some of the old school guys are overusing the static method instead of doing OOP approach.
eg:
The implementation above can be thousands of lines
This style happens everywhere to make it like OOP style (because it happen in the class) but thinking like procedural approach.
This is a help since not all people understand OOP style rather than like OOP style.
The other advantage using static are saving memory footprints and faster.
You can see in the blogs : http://www.dotnetperls.com/callvirt