The strategy mode of Java design pattern

Source: Internet
Author: User

Mind Mapping:

Let's take a look at the popular explanation of strategy design pattern:

With different types of MM dating, to use different strategies, some of the film is better, some go to eat snack effect is good, some go to the seaside romantic most suitable, but the purpose is to get mm heart, I chase mm Jin sac there are many strategy oh.
Policy mode:

The policy pattern is for a set of algorithms that encapsulate each algorithm in a separate class with a common interface so that they can be replaced with each other.

The policy pattern allows the algorithm to change without affecting the client. The strategy model separates behavior from the environment. The Environment class is responsible for maintaining and querying behavior classes, and various algorithms are available in specific policy classes. because the algorithm and the environment independent, the algorithm increases or decreases, the modification will not affect the environment and the client .

Example 1:

First define an interface, which is the interface that Zhuge Liang gave Zhao Yun three ingenious tricks.

1, the public part of the abstract as an interface;

The following interface is the public interface of the algorithm class.

 Package Com.liwei.strategy; /**  @author*/Publicinterface  istrategy    {/* *     Every coup is an algorithm     that can be executed */public     void  operate ( );}

2. Write three implementation classes

 package   Com.liwei.strategy.impl;  import   Com.liwei.strategy.IStrategy;  /**   * ingenious implementation class One *   @author   Administrator *  */ public  class  Backdoor implements   IStrategy {@Override public  void   operate () {System.out.println () Qiaoguo old back door, so that Wu will exert pressure on Sun Quan so that he cannot kill Liu Bei.    "); }}
 package   Com.liwei.strategy.impl;  import   Com.liwei.strategy.IStrategy;  /**   * ingenious implementation Class One * *   @author   Administrator *  */ public  class  Blackenemy implements   IStrategy {@Override public  void   operate () {System.out.println () neighbour, blocking the pursuers.    "); }}
 Package Com.liwei.strategy.impl; Import Com.liwei.strategy.IStrategy; /**  @author*/Publicclass implements  istrategy {    @Override    publicvoid  operate () {        System.out.println ( "Ask Wu to open a green light, the Dew Temple to rescue!" ");    }    }

3, put the implementation of the class in an environment (no need to implement the interface, can be considered as a method to provide external)

 PackageCom.liwei.strategy;/*** This is the place where the tips are stored *@authorAdministrator **/ Public classContext {Privateistrategy strategy; /*** Use constructor injection to indicate which ingenious plan you want to use *@paramStrategy*/     PublicContext (IStrategy strategy) { This. Strategy =strategy; }        /*** This is the method of the brocade sac, which produces ingenious tricks from the balloon, and the ingenious scheme is determined by the injected ingenious interface.*/     Public voidOper () {/*** This time, the real trick to come in is to really do it.*/         This. Strategy.operate (); }}

4. Write Test class

 PackageCom.liwei.strategy;ImportCom.liwei.strategy.impl.BackDoor;ImportCom.liwei.strategy.impl.BlackEnemy;ImportCom.liwei.strategy.impl.GivenGreenLight; Public classTest {/*** Here to note: is the operation of the brocade SAC *@paramargs*/     Public Static voidMain (string[] args) {context context; //when I first arrived in Wu, I opened the 1th.SYSTEM.OUT.PRINTLN ("When------first arrived in Wu, he opened the 1th capsule------"); Context=NewContext (Newbackdoor ());        Context.oper (); System.out.println ("\ n"); System.out.println ("------Then Liu Bei, began to dismantle the 2nd capsule------"); Context=NewContext (Newgivengreenlight ());        Context.oper (); System.out.println ("\ n"); System.out.println ("------Sun Quan's pursuers, and began to dismantle the 3rd sac------"); Context=NewContext (NewBlackenemy ());    Context.oper (); }}

Example 2:

1, define a common interface of the algorithm class;

This interface just defines the calculation, how to calculate? The two operands are add, subtract, multiply, divide?

 Package Com.shejimoshi.celue;  Public Interface Strategy {    publicint calculate (int A,int  b);}

2, the realization of the algorithm interface class;

 package   Com.shejimoshi.celue;  public  class  Addstrategy implements   strategy {@Override public  int  A,  b) { return  a + b; }}
 package   Com.shejimoshi.celue;  public  class  Subtractstrategy implements   strategy {@ Override  public  int  Calculate ( Span style= "color: #0000ff;" >int  A,  b) { return  a- b; }}
 Package Com.shejimoshi.celue;  Public class Implements Strategy {    @Override    publicint calculate (intint  b) {         return A * b;    }}

3, define an environment class;

 PackageCom.shejimoshi.celue; Public classEnvironment {Privatestrategy strategy;  PublicEnvironment (Strategy strategy) {Super();  This. Strategy =strategy; }     PublicStrategy Getstrategy () {returnstrategy; }     Public voidSetstrategy (Strategy strategy) { This. Strategy =strategy; }     Public intCalculateintAintb) {return  This. Strategy.calculate (A, b); }}

4, the Environment class to perform the operation.

 PackageCom.shejimoshi.celue; Public classClient { Public Static voidMain (string[] args) {/*** Understanding the Strategy design pattern pay attention to the concept of polymorphism in Java*/addstrategy addstrategy=NewAddstrategy (); Environment Environment=NewEnvironment (ADDSTRATEGY); System.out.println (Environment.calculate (4, 3)); //SubtractionSubtractstrategy Substrategy =NewSubtractstrategy ();        Environment.setstrategy (Substrategy); System.out.println (Environment.calculate (4, 3)); //multiplicationMulstrategy Multiplystrategy =NewMulstrategy ();        Environment.setstrategy (Multiplystrategy); System.out.println (Environment.calculate (4, 3)); }}

The strategy mode of Java design pattern

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.