unity游戏开发中用到的设计模式列出详细示例代码
时间: 2023-03-15 08:13:16 浏览: 137
Unity游戏开发中常用的设计模式有:工厂模式、单例模式、策略模式、观察者模式、模板模式等。下面给出示例代码:工厂模式:
public interface ICarFactory
{
Car CreateCar();
}
public class BMWFactory : ICarFactory
{
public Car CreateCar()
{
return new BMWCar();
}
}单例模式:
public class Singleton
{
private static Singleton instance;
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}策略模式:
public interface IStrategy
{
void Execute();
}
public class StrategyA : IStrategy
{
public void Execute()
{
// Execute A strategy
}
}观察者模式:
public class Subject
{
private List<Observer> observers = new List<Observer>();
public void Attach(Observer observer)
{
observers.Add(observer);
}
public void Detach(Observer observer)
{
observers.Remove(observer);
}
public void Notify()
{
foreach (var observer in observers)
{
observer.Update();
}
}
}模板模式:
public abstract class Game
{
public abstract void Initialize();
public abstract void StartPlay();
public abstract void EndPlay();
public final void Play()
{
Initialize();
StartPlay();
EndPlay();
}
}
阅读全文