CSC/ECE 517 Fall 2007/wiki1b 7 vs

From Expertiza_Wiki
Revision as of 22:44, 1 October 2007 by Snviswan (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Here is a Ruby example implementation:

module CommandPattern  
  def undoCommand()    
    if(@states.length > 0)
        initialize(@states.pop())
    else
        puts "no command done to undo"
    end
  end
  
  def doCommand(object)
    if(@states == nil)
      @states = []
    end
    
    @states.push(object)
    puts "docommand #{object}" 
  end
end
class NewString < String 
  include CommandPattern
  attr_accessor :states
  def initialize(arg)
    super(arg)
  end
  def concat(arg)
    doCommand(to_s())
    super(arg)
    
  end
end

a = NewString.new("sample")
puts a
a.concat(" test case")
puts a
a.undoCommand();
puts a
a.undoCommand()
puts a


$ irb
irb(main):001:0> puts "Hello, World"
Hello, World
=> nil
irb(main):002:0> 1+2
=> 3


Here is a JAVA example implementation: <java> import java.util.ArrayList; interface CommandPattern { void doCommand(); void undoCommand(); }

class NewString implements CommandPattern {

private ArrayList<String> states = new ArrayList(); private String s;

public NewString (String args) { s = args; }

public ArrayList<String> getStates() { return states; }

public void setStates(ArrayList<String> states) { this.states = states; }

public void concat(String args) { doCommand(); s = s.concat(args); }

public void doCommand() { states.add(this.s); }

public void undoCommand() { if(states.size() > 0) { s = states.get(states.size()-1); states.remove(states.size()-1); } else System.out.println("no command done to undo"); }

public String getS() { return s; }

public void setS(String s) { this.s = s; }

public static void main(String[] args) {

NewString s = new NewString("sample");

System.out.println(s.getS()); s.concat(" test case"); System.out.println(s.getS()); s.undoCommand(); System.out.println(s.getS()); s.undoCommand(); System.out.println(s.getS()); }

} </java>