Mememto Pattern

目的

实现撤销编辑功能。在编辑文字、编辑图片、编辑视频等项目会用到。

代码实例

实现文章编辑的回退功能:

Article类:

package com.cong.designpattern.memento;

public class Article {
    private String content;
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public ArticleState createState() {
        return new ArticleState(this.content);
    }
    public void restoreState(ArticleState state) {
        this.content = state.getContent();
    }
}

ArticleState类:

package com.cong.designpattern.memento;

public class ArticleState {
    private String content;
    public ArticleState(String content) {
        this.content = content;
    }
    public String getContent() {
        return content;
    }
}

ArticleHistory类:

package com.cong.designpattern.memento;

import java.util.ArrayList;
import java.util.List;

public class ArticleHistory {
    private List<ArticleState> list;
    public ArticleHistory() {
        this.list = new ArrayList<>();
    }
    public void push(ArticleState state) {
        this.list.add(state);
    }
    public ArticleState pop() {
        int lastIndex = this.list.size() - 1;
        if (lastIndex < 0) return null;

        ArticleState state = this.list.get(lastIndex);
        this.list.remove(lastIndex);
        return state;
    }
}

测试代码:

package com.cong.designpattern;

import android.util.Log;

import com.cong.designpattern.memento.Article;
import com.cong.designpattern.memento.ArticleHistory;

public class Test {
    private static String TAG = "Test";

    public static void doTest() {
        Article article = new Article();
        ArticleHistory history = new ArticleHistory();

        article.setContent("a");
        history.push(article.createState());
        article.setContent("b");
        history.push(article.createState());
        article.setContent("c");

        article.restoreState(history.pop());

        Log.d(TAG, "doTest: "+ article.getContent());
    }
}

UML

Memento Pattern UML
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容