JAVA design mode-policy mode (strategy) __java

Source: Internet
Author: User

definition: defines a series of algorithms, encapsulates them, and allows them to be replaced by each other. This mode allows the algorithm to vary independently from the customer who uses it.

Type: object behavior pattern

class Diagram:

The strategy pattern is the encapsulation of the algorithm, which encapsulates a series of algorithms into the corresponding classes, and these classes implement the same interface and can be replaced by each other. In the behavior class pattern mentioned earlier, there is a pattern is also concerned about the encapsulation of the algorithm-template method mode, compared to the class diagram can be seen, the policy model and template method model is only a separate package of the context, it and template method mode is the difference between: in the Template method mode, The principal of the calling algorithm is in the abstract parent class, and in the policy pattern, the principal of the calling algorithm is encapsulated into the encapsulation class context, and the abstract policy strategy is generally an interface, intended only to define the specification, which generally does not contain logic. In fact, this is only a common implementation, and in real programming, because the various specific policy implementation classes inevitably exist between some of the same logic, in order to avoid duplicate code, we often use abstract classes to serve as the role of strategy, in the package of common code, so, in many application scenarios, In the policy mode, you will generally see the shadow of the template method pattern.

structure of the policy pattern Encapsulation Class (context): also called contexts, the policy is encapsulated two times in order to avoid the high-level module on the policy call directly. abstract Policy: typically an interface, when duplicate logic exists in each implementation class, an abstract class is used to encapsulate this part of the common code, at which point the policy pattern looks more like a template method pattern. Specific strategy: the specific policy role is usually performed by a set of classes that encapsulate the algorithms, which can be freely replaced as needed.

Policy Pattern Code implementation [Java]  View plain copy interface istrategy {       public void  DoSomething ();  }   class concretestrategy1 implements istrategy {        public void dosomething ()  {            SYSTEM.OUT.PRINTLN ("Specific Strategy 1");       }  }    class concretestrategy2 implements istrategy {        public void dosomething ()  {            SYSTEM.OUT.PRINTLN ("Specific Strategy 2");       }  }   Class context  {       private IStrategy strategy;               public context (istrategy strategy) {            this.strategy = strategy;       }               public void execute () {           strategy.dosomething ();       }   }      public class client {        Public static void main (String[] args) {            Context context;            SYSTEM.OUT.PRINTLN ("-----Execution Strategy 1-----");           context  = new context (New concretestrategy1 ());            context.execute ();               SYSTEM.OUT.PRINTLN ("-----Execution Policy 2-----");           context = new context (new  ConcreteStrategy2 ());           context.execute ();        }  }  

advantages and disadvantages of the strategy model

Advantages:

Correlation algorithm Series strategy class hierarchy defines a series of algorithms or behaviors that can be reused for the context. Inheritance helps to extract public functionality from these algorithms.
An alternative to inherited method inheritance provides another way to support multiple algorithms or behaviors. You can generate a subclass of the context directly to give it a different behavior. But this will encode the behavior into the context, and combine the implementation of the algorithm with the implementation of the context, making the context difficult to understand, difficult to maintain, and difficult to extend, and not be able to change the algorithm dynamically. Encapsulating the algorithm in a separate strategy class allows you to change it independently of the context, making it easy to switch, understand, and expand.
Eliminating some conditional statements The strategy pattern provides an alternative to choosing the desired behavior with a conditional statement.
The implementation of the Select strategy pattern can provide different implementations of the same behavior. Customers can choose from different policies based on different time/space trade-offs.
Disadvantages:

Customers must understand different strategy a customer needs to choose a suitable strategy must know how these strategy are different. You may have to disclose specific implementation issues to your customers at this point. Therefore, you need to use the Strategy mode only when these different behavioral variants are related to the behavior of the customer.
Strategy and context direct communication overhead regardless of the strategy, context implementation of the algorithm is simple or complex, they all share strategy defined interface.
Increased number of objects strategy increases the number of objects in an application.


Applicable Scenarios

Use strategy when the following scenario is present:

Many of the related classes are simply behavioral differences. Policy provides a way to configure a class by one behavior in multiple behaviors. You need to use different variants of an algorithm. The algorithm uses data that the customer should not know about. Policy patterns can be used to avoid exposing complex, algorithmic-related data structures. A class defines a variety of behaviors, and these behaviors appear in the form of multiple conditional statements in the operation of this class. The related conditional branches are moved into their respective strategy classes to override these conditional statements.

The strategy pattern is a kind of simple commonly used pattern, we in the development, will often intentionally or unintentionally use it, generally speaking, the strategy pattern does not use alone, with the template method pattern, the factory pattern and so on mixes uses the situation to be more.

Contact Us

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.