In most cases, template method and strategy can complete the same task, that is, to complete the task in a certain step without relying on the implementation of specific steps. The implementation of the specific step of template method downgrading is left to the subclass, while Strategy leaves the specific implementation to any class that follows a specific interface. The vast majority of frameworks can find at least one of them. The difference between the two is that the template method uses inheritance to achieve the goal. Inheritance is a type of strong coupling, which makes the subclass dependent on the parent class. Its disadvantages lie in the sub-class Code It also needs to be reflected in the replay. Detailed examples are available in Agile Software Development of Uncle Bob: For most orders Algorithm Swap and outoforder are all necessary operations. Therefore, they do not become subclasses of an algorithm. Strategy provides more loose coupling, and its swap and outoforder can also
Used by many different algorithms. "
Used by many different algorithmsThis determines whether or not to use strategy. That is, when the implementation of your specific step is not only used by the parent class, but also needs to be used by other classes, it's time for strategy. In fact, the difference between the two is the difference between inheritance and combination. The actual example can be the Controller mechanism in the Web framework. Most of them are strategy. There is a master servlet responsible for parsing URLs and distributing requests to the next level controller (such as the action in struts or the Controller of spring). These next level controllers are strategy, implemented by the user. If this is the case, the template method can be competent, just inherit the master control servlet (like Oscar), after all, these subclasses are often not used by other code. However, if Preprocessor and postprocessor are required, you must use strategy. These processors are often used to process some common things, and many controllers will use them. Still using template method causes code duplication.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service