小鸟游星野
小鸟游星野
Published on 2025-05-22 / 4 Visits
0
0

简单工厂设计模式(暂时)

一、工厂设计模式(Factory Pattern)

核心思想

将对象的创建和使用分离,通过统一的接口创建对象,避免直接在代码中硬编码 newInstantiate,提高灵活性和可扩展性。

Unity 中的典型应用场景

  • 动态生成敌人、子弹、道具等游戏对象

  • 根据配置创建不同类型的角色或UI元素

实现示例:简单工厂模式

// 1. 定义敌人接口
public interface IEnemy {
    void Attack();
}

// 2. 实现具体敌人类型
public class Goblin : MonoBehaviour, IEnemy {
    public void Attack() => Debug.Log("Goblin attacks with a club!");
}

public class Skeleton : MonoBehaviour, IEnemy {
    public void Attack() => Debug.Log("Skeleton shoots an arrow!");
}

// 3. 工厂类
public static class EnemyFactory {
    public static IEnemy CreateEnemy(EnemyType type) {
        switch (type) {
            case EnemyType.Goblin:
                return new GameObject("Goblin").AddComponent<Goblin>();
            case EnemyType.Skeleton:
                return new GameObject("Skeleton").AddComponent<Skeleton>();
            default:
                throw new ArgumentException("Invalid enemy type");
        }
    }
}

// 4. 使用工厂
IEnemy enemy = EnemyFactory.CreateEnemy(EnemyType.Goblin);
enemy.Attack();

优点

  • 解耦创建逻辑:新增敌人类型时只需修改工厂类

  • 统一管理对象池:可集成对象池优化性能


Comment