开发者

Static method Uses

开发者 https://www.devze.com 2023-04-12 06:00 出处:网络
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开发者_StackOverfl

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开发者_StackOverflow社区 object. Why should we have static method. Can someone provide a example to explain?


Static methods can be useful when you have private constructors, because you want to abstract the instantiation process.

For example in C++:

class Foo {
  Foo() {}
public:
  static Foo *create() {
    return new Foo;
  }
};

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.:

struct Foo;

struct Bar {
  Bar() : f(make()) {
  }

private:
  const Foo f;

  static Foo make() {
    // Create it here
  }
};


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 :

  public class People
  {
      private
      public static Int32 GetValue(Int x)
      {
          return x + 3;
      }
  }

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:

public class People
{
    public static DataSet GetPeopleById(String personId)
    {  .... implementation that using SQL query or stored procedure and return dataset ... }

    public static DataSet GetXXXXXXX(String name, DateTime datex)
    { .... implementation ... }
}

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号