Created
May 17, 2012 16:50
-
-
Save dtinth/2720151 to your computer and use it in GitHub Desktop.
Example of using Polymorphism for Strategy/Command pattern in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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