Unity 设计模式之 模板方法模式的实例介绍

2025-10-19 13:03:43

1、模板方法模式:

       定义一个操作中的算法的股价,而将一些步骤延迟到子类中,模板方法使得子类可以不改变一个算法的结构即可冲定义该算法的某些特定步骤。

Unity 设计模式之 模板方法模式的实例介绍

2、模式中的角色:

       1)AbstractClass(抽象的类):实现了一个模板方法,定义了算法的骨架,具体子类降重定义 PrimitiveOpertion 以实现一个算法的步骤;

       2)ConcreteClass(具体的类):实现 PrimitiveOperation 已完成算法中与特定子类相关的步骤;

3、模板方法模式的使用实例:

Unity 设计模式之 模板方法模式的实例介绍

1、打开Unity,新建一个空工程,具体如下图

Unity 设计模式之 模板方法模式的实例介绍

2、在工程中,新建几个脚本,然后双击打开,具体如下图

Unity 设计模式之 模板方法模式的实例介绍

3、脚本的具体代码和代码说明如下图

Unity 设计模式之 模板方法模式的实例介绍

Unity 设计模式之 模板方法模式的实例介绍

Unity 设计模式之 模板方法模式的实例介绍

Unity 设计模式之 模板方法模式的实例介绍

4、TestPaperTemplateClass 脚本具体内容如下:

using UnityEngine;

public class TestPaperTemplateClass  {

    public  void TestQuestion1(){

        Debug.Log ("1 + 2 = [ ]   a.2  b.1  c.3");

        Debug.Log ("答案:" + Answer1 ());

    }

    public virtual string Answer1(){

        return "";

    }

    public  void TestQuestion2(){

        Debug.Log ("1 * 2 = [ ]   a.2  b.1  c.3");

        Debug.Log ("答案:" + Answer2 ());

    }

    public virtual string Answer2(){

        return "";

    }

}

5、TestPaperAConcreteClass 脚本具体内容如下:

public class TestPaperAConcreteClass : TestPaperTemplateClass {

    public override string Answer1 ()

    {

        return "a";

    }

    public override string Answer2 ()

    {

        return "b";

    }

}

6、TestPaperBConcreteClass 脚本具体内容如下:

public class TestPaperBConcreteClass : TestPaperTemplateClass {

    public override string Answer1 ()

    {

        return "c";

    }

    public override string Answer2 ()

    {

        return "a";

    }

}

7、Test 脚本具体内容如下:

using UnityEngine;

public class Test : MonoBehaviour {

    // Use this for initialization

    void Start () {

        Debug.Log ("TestPaperA :");

        TestPaperAConcreteClass testPaperA = new TestPaperAConcreteClass ();

        testPaperA.TestQuestion1 ();

        testPaperA.TestQuestion2 ();

        Debug.Log ("TestPaperB :");

        TestPaperBConcreteClass testPaperB = new TestPaperBConcreteClass ();

        testPaperB.TestQuestion1 ();

        testPaperB.TestQuestion2 ();

    }

}

8、脚本编译正确,回到Unity界面,在场景中新建一个 GameObject,并把 Test 脚本赋给 GameObject,具体如下图

Unity 设计模式之 模板方法模式的实例介绍

9、运行场景,控制台 Console 打印如下图

Unity 设计模式之 模板方法模式的实例介绍

10、到此,《Unity 设计模式之 模板方法模式的实例介绍》讲解结束,谢谢

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢