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

2025-04-13 09:13:13

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

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

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

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

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

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

4、TestPaperTemplateClass 脚本具体内容如下:using曷决仙喁UnityEngine;publicclassTestPaperTemplateClass{pub造婷用痃licvoidTestQuestion1(){ Debug.Log("1+2=[]a.2b.1c.3"); Debug.Log("答案:"+Answer1()); }publicvirtualstringAnswer1(){ return""; }publicvoidTestQuestion2(){ Debug.Log("1*2=[]a.2b.1c.3"); Debug.Log("答案:"+Answer2()); } publicvirtualstringAnswer2(){ return""; }}

5、TestPaperAConcreteClass脚本具体内容如下:publi罕铞泱殳cclassTestPaper帆歌达缒AConcreteClass:TestPaperTemplateClass{publicoverridestringAnswer1() { return"a"; }publicoverridestringAnswer2() { return"b"; }}

6、TestPaperBConcreteClass脚本具体内容如下:publi罕铞泱殳cclassTestPaper蚱澄堆别BConcreteClass:TestPaperTemplateClass{publicoverridestringAnswer1() { return"c"; }publicoverridestringAnswer2() { return"a"; }}

7、Test脚本具体内容如下:usingUnityEngine;publicc盟敢势袂lassTest:MonoBehaviour{//Usethisforinitialization voidStart(){Debug.Log("TestPaperA:"); TestPaperAConcreteClasstestPaperA=newTestPaperAConcreteClass(); testPaperA.TestQuestion1(); testPaperA.TestQuestion2();Debug.Log("TestPaperB:"); TestPaperBConcreteClasstestPaperB=newTestPaperBConcreteClass(); testPaperB.TestQuestion1(); testPaperB.TestQuestion2();}}

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

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

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

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

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

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