Intention
Define a series of algorithms, encapsulate them one by one, and make them interchangeable with each other. This mode allows the algorithm to be independent of the customers who use it.
The strategy mode is used in the algorithm decision-making system, the external user only needs to decide which algorithm to use.
Public interface ICalculator {public int calculate (String exp); }
Public abstract class Abstractcalculator {public int[] Split (string exp,string opt) { string array[] = Exp.split ( opt); int arrayint[] = new int[2]; Arrayint[0] = Integer.parseint (array[0]); ARRAYINT[1] = Integer.parseint (array[1]); return arrayint; }
public class Plus extends Abstractcalculator implements ICalculator { @Override public int Calculate (String EXP) { int arrayint[] = Split (exp, "\\+"); return arrayint[0]+arrayint[1]; }
public class minus extends Abstractcalculator implements ICalculator { @Override public int calculate (String exp ) { int arrayint[] = Split (exp, "-"); return arrayint[0]-arrayint[1]; } }
Test
public class Strategytest {public static void Main (string[] args) { ICalculator cal = new Plus (); int result = Cal.calculate ("2+8"); SYSTEM.OUT.PRINTLN (result); } }
Transferred from: http://blog.csdn.net/zhangerqing/article/details/8243942
Java Learning notes-design pattern 14 (policy mode)