Skip to content

Instantly share code, notes, and snippets.

@dtinth
Created May 17, 2012 16:50
Show Gist options
  • Save dtinth/2720151 to your computer and use it in GitHub Desktop.
Save dtinth/2720151 to your computer and use it in GitHub Desktop.
Example of using Polymorphism for Strategy/Command pattern in Java
import java.util.Scanner;
interface Operator {
int calc(int a, int b);
}
class Add implements Operator {
public int calc(int a, int b) { return a + b; }
}
class Sub implements Operator {
public int calc(int a, int b) { return a - b; }
}
class Mul implements Operator {
public int calc(int a, int b) { return a * b; }
}
class Div implements Operator {
public int calc(int a, int b) { return a / b; }
}
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("number #1 : ");
int n1 = s.nextInt();
System.out.print("operator : ");
String o = s.next();
System.out.print("number #2 : ");
int n2 = s.nextInt();
Operator op = getOperator(o);
System.out.println(op.calc(n1, n2));
}
public static Operator getOperator(String s) {
if (s.equals("+")) return new Add();
if (s.equals("-")) return new Sub();
if (s.equals("*")) return new Mul();
if (s.equals("/")) return new Div();
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment