美文网首页
模板方法模式

模板方法模式

作者: 金煜博 | 来源:发表于2021-05-02 10:24 被阅读0次

什么模板方法?

在抽象类中定义一个方法模板,将确定的方法放入抽象类中实现,抽象不确定的方法由子类继承实现。

示例场景描述

街坊找18-30岁之间的路人回答指定的问题。
(问题兴趣 居住为不确定的 问题年龄是确定的)

示例图

图片.png

示例代码

1.创建街坊问题抽象类

public abstract class NeighborhoodProblem {
    protected String name;

    protected NeighborhoodProblem(String name) {
        this.name = name;
    }

    public final void problem() {
        interst();
        ageGroup();
        resideuce();
    }

    protected abstract void resideuce();

    protected void ageGroup() {
        System.out.println("年龄段在18-30岁");
    }

    protected abstract void interst();
}

2.创建路人1和路人2

public class PeopleOne extends NeighborhoodProblem {

    protected PeopleOne(String name) {
        super(name);
    }

    @Override
    protected void resideuce() {
        System.out.println("一号采访人" + name + "居住在上海");
    }

    @Override
    protected void interst() {
        System.out.println("一号采访人" + name + "喜欢看电影");
    }


}
public class PeopleTwo extends NeighborhoodProblem {
    protected PeopleTwo(String name) {
        super(name);
    }

    @Override
    protected void resideuce() {
        System.out.println("二号采访人" + name + "居住在北京");
    }

    @Override
    protected void interst() {
        System.out.println("二号采访人" + name + "喜欢打篮球");
    }
}

3.启动类

public class Test {
    public static void main(String[] args) {
        PeopleOne peopleOne = new PeopleOne("小橙子");
        peopleOne.problem();
        System.out.println("--------------------------------------------------------------------------------------");
        PeopleTwo peopleTwo = new PeopleTwo("阿亮");
        peopleTwo.problem();
    }
}

4.运行结果


图片.png

相关文章

网友评论

      本文标题:模板方法模式

      本文链接:https://www.haomeiwen.com/subject/yortdltx.html