The strategy pattern of Java design pattern detailed _java

Source: Internet
Author: User
Tags wrapper

The example of this article for everyone to share the Java strategy model for your reference, the specific contents are as follows

1, the Strategic model (strategy pattern) is a relatively simple model, also known as the Policy Model (Policypattern).
The definition is as follows:

Define a family of algorithms,encapsulate each one,and make them interchangeable.
(defines a set of algorithms that encapsulate each algorithm and make them interchangeable.) )

The generic class diagram for the policy pattern is as follows:

Three roles for a policy pattern:
Context Encapsulation role
It is also called the contextual role, which acts as a wrapper, shielding the high-level module from the direct access to the strategy, the algorithm, and encapsulating the possible changes.

Strategy Abstract Policy role
The abstraction of a policy, algorithm family, usually an interface that defines the methods and attributes that each policy or algorithm must have,

Concrete strategy specific policy roles
Implements an action in an abstract policy that contains a specific algorithm.

The policy pattern is to pass a specific policy into the wrapper role's constructor, and then execute the policy.

The strategy mode common source code is as follows:

public class Test3 {public 
 static void Main (string[] args) { 
    
  //Declare a specific policy 
   strategy strategy = new Concretestra Tegy1 (); 
   Declares context object Contexts 
   = new strategy; 
   Execute the Encapsulated method 
   Context.doanythinig (); 
 
 
   
 } 
 
Interface Strategy { 
 //policy-mode algorithms public 
 void DoSomething (); 
} 
 
Class ConcreteStrategy1 implements strategy {public 
  
 void dosomething () { 
   System.out.println ("Algorithm for specific policy 1"); 
 } 
} 
Class ConcreteStrategy2 implements strategy {public  
  
 void dosomething () { 
   System.out.println ("Algorithm for specific Policy 2"); 
 } 
} 
 
Class Context { 
 //abstract strategy 
 Private strategy strategy; 
 constructor sets the specific policy public context 
 (strategy _strategy) { 
   this.strategy = _strategy; 
 } 
 The encapsulated policy method public 
 void Doanythinig () { 
   this.strategy.doSomething (); 
 } 

advantages of the policy model:

The algorithm is free to switch

This is defined by the policy pattern itself, and as long as the abstract policy is implemented, it becomes a member of the policy family and encapsulates it by encapsulating the role, guaranteeing a "free handoff" strategy.

Avoid using multiple conditional judgments

If there is no policy model, let's think about what it would look like. A policy family has 5 policy algorithms, one to use a policy, one to use
b strategy, how to design it? Use multiple conditional statements? Multiple conditional statements are not easy to maintain, and the probability of error is greatly enhanced. After using the policy mode, it is possible for other modules to decide which policy to adopt, and the access interface provided by the policy family is the encapsulation class, simplifying the operation and avoiding the conditional statement judgment.

Good scalability

It doesn't even have to be a virtue, because it's too obvious. Adding a policy to an existing system is too easy, as long as the interface is implemented, and nothing else is modified, similar to a plug-in that can be repeatedly disassembled, which is in line with the OCP principle.

Disadvantages of the policy model:
Increased number of policy classes each strategy is a class, the likelihood of reuse is very small, and the number of classes increases.
All policy classes need to be exposed to the outside world

Usage scenarios for policy patterns:
Multiple classes have only a slightly different scenario on the algorithm or behavior.
The algorithm needs to be free to switch scenes.
A scenario that requires masking algorithm rules.

2. Extension of policy pattern-policy enumeration

The policy enumeration is defined as follows:
It is an enumeration.
It is an enumeration of a condensed policy pattern.
Examples are as follows:
Title: Input 3 parameters, add subtraction operation, the parameters are two int, one of the remaining parameters is string type, only "+", "-" two symbols can choose, do not consider what complex checksum, we do is the white box test, Input is the standard int type and the compliance string type.

Import Java.util.Arrays; 
 
 
public class Test3 {public 
 static void Main (string[] args) { 
    
  //Input two parameters are numeric 
  int a = Integer.parseint (Args[0]); 
  String symbol = args[1];//symbol 
  int b = Integer.parseint (args[2]); 
  SYSTEM.OUT.PRINTLN ("Input parameters are:" +arrays.tostring (args)); 
  SYSTEM.OUT.PRINTLN ("Run result is:" +a+symbol+b+ "=" +calculator.add.exec (a,b)); 
 
 
 
   
 } 
Enum Calculator { 
 //addition Operation 
 ADD ("+") {public 
   int exec (int a,int b) {return 
     a+b} 
   } 
 , 
 Subtraction Operation 
 SUB ("-") {public 
   int exec (int a,int b) {return 
     a-b; 
   } 
 }; 
 String value = ""; 
  
 Define member value type 
 private Calculator (String _value) { 
   this.value = _value; 
 }  
  
 Gets the value of the enumeration member public 
 String GetValue () {return 
   this.value; 
 } 
 Declares an abstract function public 
 abstract int exec (int a,int b); 
} 

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.