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.
相关问题
- Delete Messages from a Topic in Apache Kafka
- how to define constructor for Python's new Nam
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
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
Comparator
s can be used to sort, if a class does not implementComparable
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.
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.