Reputation: 8937
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?
Upvotes: 3
Views: 202
Reputation: 5265
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.
Upvotes: 0
Reputation: 131
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
Upvotes: 1
Reputation: 6490
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) e.g methods operating on the same set of instance variables (fields) belong together to an instance.
Upvotes: 4
Reputation: 69250
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.
Upvotes: 4
Reputation: 223207
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.
Upvotes: 5