Step 1: Define the interface
public interface ICalculator { public int calculate(String exp); }
Step 2: Define an abstract class (optional, for assistance)
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; } }
Step 3: Define the implementation class, inherit the abstract class, and implement the interface
public class Minus extends AbstractCalculator implements ICalculator{ @Override public int calculate(String exp) { int[] arrayInt=split(exp,"-"); return arrayInt[0]-arrayInt[1]; } }
Step 4: Test
public class StrategyTest { public static void main(String[] args) { String exp="2+8"; ICalculator cal=new Plus(); int result=cal.calculate(exp); System.out.println("2+8="+result); } }