0

我需要为下面的复杂对象编写撤消/重做功能。

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 值,但不适用于复杂的对象。它似乎包含一个引用而不是那个对象。有什么方法可以使它工作或使撤消/重做功能更容易。

4

0 回答 0