简体   繁体   中英

Static vs Instance method usage

I have a class that has some methods, which I use in code. Their aim is to generate an object and return it for further usage. I can implement it in two ways. The first way - is to make it static, like this:

public static class Builder
{
    public static MyObject BuildMyObject(Settings myEnumSetting, int someParam)
    {
        //Building object 
        return MyObject;
    }

    //Other methods          
}

Other way - is to make it instance like this:

public class Builder
{
    public MyObject BuildMyObject(Settings myEnumSetting, int someParam)
    {
        //Building object 
        return MyObject;
    }

    //Other methods          
}

In the first way can create my objects like this:

MyObject obj = Builder.BuildMyObject(Settings.Worker,20);

In the second case I can use it like this:

MyObject obj = new Builder().BuildMyObject(Settings.Worker,20);

Which of these approaches it more efficient for usage?

Which of these approaches it more efficient for usage?

It depends on your requirement, if the sole responsibility of your class is to create an object and return it then the first option with static class is better.

Using a static method is more simple. An instance method opens up for an inheritance hierarchy of builders, where you use some kind of dependency inject to select what builder to use.

If the static method works - use it for now. You can always convert the static method to a facade that hides the details of an hierarchy of inherited builder classes later.

By the way: I'd use the name Factory instead of Builder as this is an example of a factory method pattern implementation. Builder is another (more complex) pattern.

The concept you describe is called Factory Pattern. Typically a builder does not use any instance members therefore it should be static.

Instances should be used when there is a cohesion of members ( http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29 ) eg methods operating on the same set of instance variables (fields) belong together to an instance.

If this class just returns a new object then i'll think that the static way is the better one, because you are not storeing data in that class or something else.

So the static way is more efficient than the other. (I'll don't think that it would be useful to create 10 objects of this class for example)

Your class is a factory class / pattern

the advantage of a static (factory) class is, that you can keep track of the objects being created in some static property. Depending on your requirements, that might be very useful to have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM