设计模式(java版)——行为型——模板方法

项目源码已提交github:https://github.com/ckl001/designPattem_java

package com.Ljava.design.pattem.behavioral.templatemethod;

/**
 * @Auther 20173
 * @Date 2019-4-15 14:07
 * @Des TODO
 **/
public abstract class ACourse {

    protected final void makeCourse(){
        this.makePPT();
        this.makeVideo();
        if(needWriteArticle()){
            this.writeArticle();
        }
        this.packageCourse();
    }

    final void makePPT(){
        System.out.println("制作PPT");
    }
    final void makeVideo(){
        System.out.println("制作视频");
    }
    final void writeArticle(){
        System.out.println("编写手记");
    }
    //钩子方法
    protected boolean needWriteArticle(){
        return false;
    }
    abstract void packageCourse();

}

package com.Ljava.design.pattem.behavioral.templatemethod;

/**
 * @Auther 20173
 * @Date 2019-4-15 14:23
 * @Des TODO
 **/
public class DesignPatternCourse extends ACourse {
    @Override
    void packageCourse() {
        System.out.println("提供课程Java源代码");
    }

    @Override
    protected boolean needWriteArticle() {
        return true;
    }

}

package com.Ljava.design.pattem.behavioral.templatemethod;

/**
 * @Auther 20173
 * @Date 2019-4-15 14:19
 * @Des TODO
 **/
public class FECourse extends ACourse {
    private boolean needWriteArticleFlag = false;

    @Override
    void packageCourse() {
        System.out.println("提供课程的前端代码");
        System.out.println("提供课程的图片等多媒体素材");
    }

    public FECourse(boolean needWriteArticleFlag) {
        this.needWriteArticleFlag = needWriteArticleFlag;
    }

    @Override
    protected boolean needWriteArticle() {
        return this.needWriteArticleFlag;
    }
}

package com.Ljava.design.pattem.behavioral.templatemethod;

/**
 * @Auther 20173
 * @Date 2019-4-15 14:24
 * @Des TODO
 **/
public class Test {

    public static void main(String[] args) {
        System.out.println("前端课程start---");
        ACourse feCourse = new FECourse(false);
        feCourse.makeCourse();
        System.out.println("前端课程end---");


        System.out.println("后端设计模式课程start---");
        ACourse designPatternCourse = new DesignPatternCourse();
        designPatternCourse.makeCourse();
        System.out.println("后端设计模式课程end---");
    }
}

你可能感兴趣的:(java基础,设计模式,(java版),设计模式,(java版))