前言:
本博客是个人博客,仅供个人学习使用。博主为一名游戏开发爱好者,结合现有的游戏开发经验,来对设计模式和实际开发进行简单的结合,但本人技术较差,还请各位大佬多多指教!
面向对象:
继承,多态,封装。这三个特性目的就是将紧耦合的代码解耦合,让程序在改动时更加简单易懂。
例子:使用简单工厂方法创建物体
工厂类+测试类(应该不用继承monobehavior,这里懒得写测试类,直接把factory挂到物体上测试)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Factory:MonoBehaviour
{
public List<GameObject> Objs;
public static MyObject creatObject(string name)
{
MyObject myObject = null;
switch (name)
{
case "cube":
myObject = new CreatCube();
break;
case "sphere":
myObject = new CreatCube();
break;
}
return myObject;
}
void Start()
{
MyObject myObject = Factory.creatObject("cube");
myObject.CreatObj();
myObject = Factory.creatObject("sphere");
myObject.CreatObj();
}
}
抽象类和实现:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class MyObject
{
public GameObject obj;
string name;
public abstract GameObject CreatObj();
}
public class CreatCube : MyObject
{
public override GameObject CreatObj()
{
obj = GameObject.FindWithTag("Cube");
return GameObject.Instantiate(obj);
}
}
public class CreatSphere : MyObject
{
public override GameObject CreatObj()
{
obj = GameObject.FindWithTag("Sphere");
return GameObject.Instantiate(obj);
}
}