Advertisement
lucast0rres

lab05

May 11th, 2017
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. /*
  2. Design Pattern Composite:
  3.  
  4. Client => Test
  5. Component => Expression
  6. Composite => Operador
  7.  
  8.  
  9. */
  10.  
  11. abstract class Expression {
  12. //Expression left, right;
  13.  
  14. abstract float eval();
  15. abstract void add(Expression exp);
  16. //void remove (Expression exp);
  17. //Expression getChild (int index);
  18. }
  19.  
  20. class Operand extends Expression {
  21. float value;
  22.  
  23. Operand (float value) {
  24. this.value = value;
  25. }
  26.  
  27. float eval() {
  28. return this.value;
  29. }
  30.  
  31. void add(Expression exp){}
  32. void remove(Expression exp){}
  33. Expression getChild (int index){
  34. return null;
  35. }
  36. }
  37.  
  38. abstract class Operator extends Expression {
  39. Expression left, right;
  40.  
  41. void add (Expression exp){
  42. if (right == null) right = exp;
  43. else left = exp;
  44. }
  45.  
  46. float eval(){
  47. return 0;
  48. }
  49.  
  50. void remove (Expression exp){}
  51. Expression getChild (int index){
  52. return null;
  53. }
  54.  
  55. }
  56.  
  57. class Multi extends Operator {
  58. float eval (){
  59. return left.eval() * right.eval();
  60. }
  61. }
  62.  
  63. class Div extends Operator {
  64. float eval (){
  65. return left.eval() / right.eval();
  66. }
  67. }
  68.  
  69.  
  70. public class Test {
  71. public static void main (String args[]) {
  72. Expression root, m;
  73. m = new Multi ();
  74. m.add(new Operand(2));
  75. m.add(new Operand(3));
  76.  
  77. root = new Div ();
  78. root.add(new Operand(4));
  79. root.add(m);
  80.  
  81. System.out.println(root.eval());
  82. }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement