Stateless Objects good practice or not [closed]

2019-05-12 00:17发布

问题:

This is my understanding about stateless objects:Any object created from class that doesn't have class variables is a stateless object. My question is when should we write stateless classes. Is it a good habit to have stateless objects.

回答1:

Stateless objects are useful if you need to "pass functionality as a parameter". Since functions are no Objects in java, it's a practical way to pass the an object with the function as parameter.

For example Comparators can be used to sort, if a class does not implement Comparable or if you need to support sorting with different definitions of the "<"-relation. (e.g. accending / descending order; sorting by different properties ...)

A factory (see http://www.oodesign.com/factory-pattern.html) may be a stateless object. All functions of the factory may create objects and all parameters necessary to create them can be given as parameters of the functions of the factory.



回答2:

Generally, if what you have is stateless (has no instance variables, only class variables), it has no reason to ever be instantiated and shouldn't be an Object (though implementing it as a class can be useful to group related functionality together and to manage access to the static class variables).

The one case where a stateless object is justified, in my opinion, is when it's a trivial implementation of an interface. For example, an immutable Collection (eg an EmptyCollection) may want to be an object so it can be passed around and manipulated like other Collection objects, but can be implemented as stateless since it's immutable and its state can never be changed.