如何撤消/重做

时间:2013-05-08 11:07:14

标签: java undo redo

我需要为下面的复杂对象编写undo / redo函数。

class DataContainer implements Serializable{

    private PublicationType type;
    private HashMap<Enum, String> fields;
    private HashMap<Enum, String> oFields;
    private HashMap<String, String> userFields;
    private String name;

    public DataContainer(PublicationType type, HashMap<Enum, String> fields, HashMap<Enum, String> oFields, HashMap<String, String> userFields, String name) {
        this.type = type;
        this.fields = fields;
        this.oFields = oFields;
        this.userFields = userFields;
        this.name = name;
    }
...
}

我开发了这段代码。

public class ChangeManager<K> {
    int size = 0;
    Node<K> root;
    Node<K> current;
    int maxsize;

    public ChangeManager(K item) {
        size++;
        root = new Node<>(null, null, item);
        current = root;
    }
    public ChangeManager(K item, int maxsize) {
        size++;
        root = new Node<>(null, null, item);
        current = root;
        this.maxsize = maxsize+1;
    } 
    public void addChange(K item){
        size++;
        Node<K> tep  = current;
        current = new Node<>(tep, null, item);
        tep.nastepny = current;
        if(maxsize>1 &&maxsize<size){
            root = root.nastepny;
            root.poprzedni = null;
            System.gc();
        }
    }
    public void setMaxsize(int maxsize) {
        this.maxsize = maxsize+1;
    }
    public boolean canUndo(){
        if(current.poprzedni!=null)return true;
        return false;
    }
        public boolean canRedo(){
        if(current.nastepny!=null)return true;
        return false;
    }   
    public K undo(){
        if(canUndo()){
            size--;
            current = current.poprzedni;
            return current.obiekt;
        }else{
            throw new UnsupportedOperationException("Nothing to undo");
        }
    }
    public K redo(){
        if(canRedo()){
            size++;
            current = current.nastepny;
            return current.obiekt;
        }else{
            throw new UnsupportedOperationException("Nothing to redo");
        }
    }
    public int getSize(){
        return size;
    }

    public void trimToSize(int trim) {
        if (trim < size) {
            for (int i = 0; i < size - trim; i++) {
                root = root.nastepny;
                root.poprzedni = null;
                System.gc();
            }
        }
    }
    private class Node<K>{
        Node<K> poprzedni;
        Node<K> nastepny;
        K obiekt;

        public Node(Node<K> poprzedni, Node<K> nastepny, K obiekt) {
            this.poprzedni = poprzedni;
            this.nastepny = nastepny;
            this.obiekt = obiekt;
        }
    }
}

它适用于简单的String或Integer值,但它不适用于复杂对象。 它似乎包含一个引用而不是该对象。 是否有某种方法可以使其工作或使撤消/重做功能更容易。

0 个答案:

没有答案