大话设计模式-模板方法模式-2020-10-13

2020-10-14  本文已影响0人  勇往直前888

定义

定义一个操作中的算法骨架,而将一系列步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

结构图

image.png

考试卷的例子

abstract class TestPaper {
    public String testQuestion1() {
        String question = "\n第1题:\n" + "杨过得到,后来给了郭靖,练成倚天剑、屠龙刀的玄铁可能是[ ]\n"
                + "a.球磨铸铁 b.马口铁 c.高速合金钥 d.碳素纤维\n"
                + "答案:" + answer1() + "\n";
        Log.v("TestPaper", question);
        return question;
    }
    protected abstract String answer1();

    public String testQuestion2() {
        String question = "\n第2题:\n" + "杨过、程英、陆无双铲除了情花.造成[ ]\n"
                + "a.使这种植物不再害人 b.使一种珍稀物种灭绝 c.破坏了那个生物圈的生态平衡 d.造成该地区沙漠化\n"
                + "答案:" + answer2() + "\n";
        Log.v("TestPaper", question);
        return question;
    }
    protected abstract String answer2();

    public String testQuestion3() {
        String question = "\n第3题:\n" + "蓝凤凰致使华山师徒、桃谷六仙呕吐不止,如果你是大夫,会给他们开什么药[ ]\n"
                + "a.阿司匹林 b.牛黄解毒片 c.氟呱酸 d.让他们喝大量的生牛奶 e.以上全不对\n"
                + "答案:" + answer3() + "\n";
        Log.v("TestPaper", question);
        return question;
    }
    protected abstract String answer3();

    public String display() {
        return testQuestion1() + testQuestion2() + testQuestion3();
    }
}
class TestPaperA extends TestPaper {
    @Override
    protected String answer1() {
        return "b";
    }

    @Override
    protected String answer2() {
        return "c";
    }

    @Override
    protected String answer3() {
        return "a";
    }
}

class TestPaperB extends TestPaper {
    @Override
    protected String answer1() {
        return "c";
    }

    @Override
    protected String answer2() {
        return "a";
    }

    @Override
    protected String answer3() {
        return "a";
    }
}
image.png
public class TemplateMethodActivity extends AppCompatActivity {

    public static void launch(Context context) {
        if (null != context) {
            Intent intent = new Intent();
            intent.setClass(context, TemplateMethodActivity.class);
            if (!(context instanceof Activity)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            context.startActivity(intent);
        }
    }

    TextView testPaperTextView;
    TestPaperA studentA;
    TestPaperB studentB;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_template_method);
        setTitle("模板方法模式");

        testPaperTextView = findViewById(R.id.textViewTestPaper);
        studentA = new TestPaperA();
        studentB = new TestPaperB();
    }

    public void onStudentAClick(View view) {
        testPaperTextView.setText(studentA.display());
    }

    public void onStudentBClick(View view) {
        testPaperTextView.setText(studentB.display());
    }
}

Demo地址

https://gitee.com/zhangxusong888/Android/tree/master/design_pattern

上一篇 下一篇

猜你喜欢

热点阅读