小话设计模式(二十二)模板方法模式
2016-10-05 23:16
525 查看
模板方法(Template Method)模式定义一个操作中的算法的骨架,而将一些步骤延迟到子类当中去。使得子类可以不改变一个算法的结构即可重定义该算法的某些特定的步骤。
模板方法适用于以下情况:1、 一次性实现一个算法的固定部分,并将可变行为留给子类实现。
2、 各个子类中公共的行为应该被提取出来并集中到一个公共的父类中用以避免代码重复。
3、 控制子类扩展,父类提供了缺省的方法,子类可以在必要时进行扩展。
模板方法模式一种特别常用的模式,你可能在编程过程中无意中就使用了它,而你却没有意识到这是一种设计模式。
举个例子,游戏里的英雄具有三个属性:力量、敏捷和智力。并且英雄类型也分为这三种,每种英雄的计算攻击力的公式不同。
英雄定义:
public abstract class Hero { public int strength { get; private set;} public int agility { get; private set;} public int intelligence { get; private set;} public int attackPlus { get; set;} public Hero(int Str, int Agi, int Int) { strength = Str; agility = Agi; intelligence = Int; } public abstract int MainAttributeValue (); public virtual float AttackPerMainAttribute () { return 1; } public abstract string MainAttributeName (); public int CalculateAttack() { return (int)(MainAttributeValue () * AttackPerMainAttribute()) + attackPlus; } public string AttributeDescription() { return string.Format ("+{0} attack per {1}", AttackPerMainAttribute (), MainAttributeName ()); } }我们将攻击力的计算公式写在了基类里,然后由子类实现MainAttributeValue方法返回主属性值。
力量型英雄:
public class StrengthHero : Hero { public StrengthHero(int Str, int Agi, int Int) : base(Str, Agi, Int) { } public override int MainAttributeValue() { return strength; } public override string MainAttributeName () { return "Strength"; } }
敏捷性英雄:
public class AgilityHero : Hero { public AgilityHero(int Str, int Agi, int Int) : base(Str, Agi, Int) { } public override int MainAttributeValue() { return agility; } public override string MainAttributeName () { return "agility"; } }
智力型英雄:
public class IntelligenceHero : Hero { public IntelligenceHero(int Str, int Agi, int Int) : base(Str, Agi, Int) { } public override int MainAttributeValue() { return intelligence; } public override string MainAttributeName () { return "intelligence"; } }
使用:
Hero hero = new StrengthHero (10,20,8); hero.attackPlus = 29; Console.WriteLine (hero.CalculateAttack ()); Console.WriteLine (hero.AttributeDescription ());
模板方法模式是一种非常实用且常用的模式,它提供了非常良好的代码复用性。
当然这个模式也有一个缺点,因为模板方法导致了一种反向的控制结构,即父类调用子类的方法,这使得代码的可读性变差。一些语言中(例如Ruby、Lua等),父类并不需要声明一个抽象方法或者虚方法便可以直接调用子类中的方法,这无疑是增加了代码的阅读难度。
相关文章推荐
- C++设计模式[二十二]模板方法模式
- JAVA设计模式(二十二)----模板方法模式
- 乐在其中设计模式(C#) - 模板方法模式(Template Method Pattern)
- 设计模式学习笔记(十六)——Template Method模板方法模式
- 设计模式笔记 13. TemplateMethod 模板方法模式(行为型模式)
- 设计模式之模板方法模式(Template Method)
- 设计模式学习之 模板方法模式
- 深入浅出Java模式设计之模板方法模式
- 设计模式学习笔记(十六)——Template Method模板方法模式
- 设计模式——模板方法模式(TemplateMethod)
- 深入浅出Java模式设计之模板方法模式
- 设计模式系列漫谈之六 - 模板方法模式
- 设计模式笔记(十五) —— 模板方法模式
- 乐在其中设计模式(C#) - 模板方法模式(Template Method Pattern)
- 设计模式(七)[模板方法(Template Method)模式]
- 第六个设计模式之:模板方法
- 浅析设计模式之模板方法
- 设计模式一模板方法模式(spring)
- 白话设计模式--行为型模式--Template Method模式(模板方法模式)
- 设计模式(1)- 模板方法 Template Method Pattern