The implementation methods of state pattern and strategy pattern are very similar. They all use polymorphism to allocate some operations to a group of related simple classes, therefore, many people think that these two models are actually the same. However
- In the real world, Strategy (such as a product promotion strategy) and status (like a button to control the status of an elevator, or a button on the mobile phone interface to control the mobile phone) there are two completely different ideas. When we model the status and policy, this difference will lead to completely different problems. For example, State migration is the core content for state modeling. However, when selecting a policy, migration has nothing to do with this. In addition, the Policy mode allows a customer to select or provide a policy, which is completely absent in the state mode.
- A policy is a plan or scheme. By executing this plan or scheme, we can achieve a specific goal under a given input condition. A policy is a set of solutions that can be replaced with each other. Select a policy to obtain the output of the policy. The rule mode is used when different behaviors are taken in different external environments. We can refer to the strategy implementation method for creating objects in the underlying Object Builder of the Microsoft Enterprise Library.
- The State mode is different. For an object with a State that is particularly important, the state machine is used to model the state of an object. The core issue of state mode processing is State migration, in the case of many States of an object, the jump and migration process between States of each business flow is complicated. For example, if a workflow is used to approve a file, it may be created, submitted, modified, approved by the HR department, approved by the boss, rejected by the HR department, rejected by the boss, or rejected by the boss, it involves multiple role interactions and many events. In this case, it is more appropriate to use state mode (state machine) for modeling; encapsulate various states and corresponding implementation steps into a group of classes that simply inherit from an interface or abstract class, and use another Context to perform automatic state transformation between them, events are used to automatically jump between States. There is a State migration curve throughout the lifecycle, which is transparent to customers. We can refer to Microsoft's latest WWF state machine workflow Implementation ideas.
- In the state mode, the state change is determined by the internal conditions of the object. The external world only needs to care about its interface, and does not need to care about the creation and conversion of its State object. In the policy mode, the policy is determined by the external condition (C.