概述
模板方法模式是一种行为型的设计模式,主要组成部分是抽象类和子类,这个模式在实际开发中是非常常用的,在框架设计中是很重要的,将通用的抽象进行抽象,然后在具体的类的时候继承抽象方法,实现对应的功能即可。模板如下
例子:现在有很多的游戏角色,有攻击,血量,防御等属性,主要是技能不同,请抽象实现。
模板方法模式
cs
internal class Program
{
private static void Main(string[] args)
{
Priest priest = new Priest();
priest.Skill();
}
public abstract class GameCharacter//抽象的基类
{
public abstract string Name { get; }//名字
public abstract uint HP { get; }//血量
public abstract uint Attack { get; }//攻击
public abstract uint Defense { get; }//防御
public abstract int CriticalStrike { get; }//暴击
public abstract void Skill();//技能
}
public class Soldier : GameCharacter//战士
{
public override string Name => "战士";
public override uint HP => 100;
public override uint Attack => 20;
public override uint Defense => 15;
public override int CriticalStrike => 24;
public override void Skill()
{
Console.WriteLine("防御强化");
}
}
public class Master : GameCharacter//法师
{
public override string Name => "法师";
public override uint HP => 92;
public override uint Attack => 10;
public override uint Defense => 12;
public override int CriticalStrike => 33;
public override void Skill()
{
Console.WriteLine("火球术");
}
}
public class Priest : GameCharacter//牧师
{
public override string Name => "牧师";
public override uint HP => 60;
public override uint Attack => 9;
public override uint Defense => 7;
public override int CriticalStrike => 12;
public override void Skill()
{
Console.WriteLine("回复术");
}
}
}
输出结果
回复术