What Is a Class Invariant?
An invariant mode and a behavioral mode. In the process of using an object by the system, a large number of similar objects need to be created. At the same time, a large number of objects also generally have the same state. At this time, the state of the objects needs to be simplified to make them the same. The number of state objects is reduced, which reduces the consumption of resources.
Invariant mode
Right!
- Chinese name
- Invariant mode
- For example
- Weakly invariant mode
- Purpose
- Reduce resource consumption
- Classification
- statistics
- Invariant mode is divided into weak invariant mode and strong invariant mode
- In the weak invariant mode, the state of a certain class object cannot change, but the state of its subclass objects can change.
- In the strong invariant mode, the state of a class object cannot be changed, and the state of its subclass objects cannot be changed.
- Invariant patterns generally consist of only one invariant class.If you discuss the types of invariant patterns, you need to add subclasses to complete.
Conditions for invariant mode
- 1. There is no method in the immutable class to modify the state of the object.
- 2. All properties in the immutable class are private.
- 3. For other objects referenced in the immutable class, the external access permission must be set. The above conditions are met to achieve the weak invariant mode.
- 4. All methods in the invariant class should be final (for the Java language), that is, methods that cannot be replaced by subclasses.
- 5. The immutable class itself is final (for the Java language), that is, immutable classes cannot be inherited, and no subclasses exist. The above five conditions are met to achieve a strong immutable pattern.
Disadvantages of weak invariant mode
- 1. Invariant subclass objects can modify the state, that is, invariant subclasses can not be immutable.
- 2. Immutable subclasses can modify the state of the parent class, so that immutable objects become mutable objects.
The advantages and disadvantages of invariant mode
- Pros: Immutable objects are easier to maintain than mutable objects.
- Immutable objects are thread-safe.
- Disadvantages: When you need to modify the state, you need to complete it by creating a new object.
IN OTHER LANGUAGES
- An invariant mode and a behavioral mode. In the process of using an object by the system, a large number of similar objects need to be created. At the same time, a large number of objects also generally have the same state. At this time, the state of the objects needs to be simplified to make them the same. The number of state objects is reduced, which reduces the consumption of resources.