当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 设计模式系列 - 模板模式

设计模式系列 - 模板模式

2019年01月07日  | 移动技术网IT编程  | 我要评论

在模板模式中,一个抽象类公开定义了执行它的方法的方式或方法

介绍

模板模式属于行为型模式,通过将相似的业务行为抽离出来放到抽象类中暴露给上层,然后在自己子类中实现具体的业务行为,通过模板类来约束上层的业务调用。

类图描述

代码实现

1、定义抽象基类

public abstract class game
{
    public abstract void initialize();
    public abstract void startplay();
    public abstract void endplay();

    public void play()
    {
        initialize();
        startplay();
        endplay();
    }
}

2、定义业务子类

public class cricket : game
{
    public override void endplay()
    {
        console.writeline("cricket game finished");
    }

    public override void initialize()
    {
        console.writeline("cricket game initialized!start palying");
    }

    public override void startplay()
    {
        console.writeline("cricket game started.enjoy the game");
    }
}

public class football : game
{
    public override void startplay()
    {
        console.writeline("football game started.enjog the game");
    }

    public override void initialize()
    {
        console.writeline("football game initialized.start playing.");
    }

    public override void endplay()
    {
        console.writeline("football game finished.");
    }
}

3、上层调用

class program
{
    static void main(string[] args)
    {
        game game = new cricket();
        game.play();

        game = new football();
        game.play();

        console.readkey();
    }
}

总结

模板方法类似在建造房子时先将房子的整体框架搭建后,然后具体的建筑细节放到建筑这个地方的时候再具体考虑,延迟的业务的构造。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网