说说-设计模式之模板方法模式

本文介绍模板方法模式的概念及其应用案例,展示了如何通过定义算法骨架来允许子类提供具体实现,从而实现代码复用和易于扩展的目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模板:如微信公众号消息模板,又比如制作不同种类的豆浆,又比如制作不同的包子等 他们中都有共同的方法,将其形成一个统一的样板。进行扩展。

行为型--->模板方法模式定义了一个算法的步骤,并允许子类别为一个或多个步骤提供其实践方式。让子类别在不改变算法架构的情况下,重新定义算法中的某些步骤。

优点:1.抽取公共部分代码,便于维护。 2.封装不变的部分,扩展相对应的部分。3.行为父类定义,子类实现。

缺点:子类越来越多。

百度百科

案例:

抽象类抽取共同的方法:

public abstract class PaperData {
    //简单题
    public void simpleQuestion() {
        System.out.println("从ABCD选择一个正确的选项" + simpleQuestionAnswer());
    }

    //多选题
    public void choiceQuestion() {
        System.out.println("从ABCD选择至少一个正确的选项" + choiceQuestionAnswer());
    }

    //简答题
    public void contenQuestion() {
        System.out.println("地球还有多少寿命?");
        System.out.println("简答题答案:" + contenQuestionAnswer());
    }

    final void getAnswer() {
        this.simpleQuestion();
        this.choiceQuestionAnswer();
        this.contenQuestionAnswer();
    }

    //答案
    protected abstract String simpleQuestionAnswer();

    protected abstract String choiceQuestionAnswer();

    protected abstract String contenQuestionAnswer();
}

子类实现

public class StudentOne extends PaperData {
    @Override
    protected String simpleQuestionAnswer() {
        return "A";
    }

    @Override
    protected String choiceQuestionAnswer() {
        return "BC";
    }

    @Override
    protected String contenQuestionAnswer() {
        return "不知道";
    }
}
public class StudentTwo extends PaperData {
    @Override
    protected String simpleQuestionAnswer() {
        return "A";
    }

    @Override
    protected String choiceQuestionAnswer() {
        return "BC";
    }

    @Override
    protected String contenQuestionAnswer() {
        return "我也不知道";
    }
}

 考试:

public class Client {
    public static void main(String[] args) {
        StudentOne studentOne=new StudentOne();
        studentOne.getAnswer();
        System.out.println("----------------------");

        StudentTwo studentTwo=new StudentTwo();
        studentTwo.getAnswer();
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值