模板模式(Template)

定义

一个抽象类公开定义了执行它的方法的方式/模板。它的子类可以按需要重写方法实现,但调用将以抽象类中定义的方式进行。这种类型的设计模式属于行为型模式。
模板模式是基于继承的。

角色

抽象模板
具体实现

实例

创建一个抽象模板,它的模板方法用final修饰

public abstract class Game {
    abstract void initialize();
    abstract void startPlay();
    abstract void endPlay();

    public final void play(){
        initialize();
        startPlay();
        endPlay();
    }
}

创建具体实现类

public class Football extends Game {
    @Override
    void initialize() {
        System.out.println("football game initialized, start playing");
    }

    @Override
    void startPlay() {
        System.out.println("football game started, enjoy the game");
    }

    @Override
    void endPlay() {
        System.out.println("football game finished!");
    }
}
public class Basketball extends Game {
    @Override
    void initialize() {
        System.out.println("basketball game initialized, start playing");
    }

    @Override
    void startPlay() {
        System.out.println("basketball game started, enjoy the game");
    }

    @Override
    void endPlay() {
        System.out.println("basketball game finished!");
    }
}

调用模板方法

public class Test {
    public static void main(String[] args) {
        Game game = new Football();
        game.play();
    }
}

运行结果

football game initialized, start playing
football game started, enjoy the game
football game finished!

你可能感兴趣的:(模板模式(Template))