OOP选型:农场模拟游戏作物实现应选子类还是枚举Enum方案?
作物逻辑实现方案建议
直接给结论:你列的两种方案都不是最优解,更推荐用数据驱动的统一Crop类方案,完全能解决你现在的冗余代码问题,后期维护成本也最低。
现有两种方案的弊端
- 方案1(子类继承):纯滥用继承,所有子类的行为逻辑完全一致,仅属性值不同,每新增一种作物就要新建一个子类,冗余代码会越堆越多,后续要修改作物公共逻辑需要同步调整所有子类,维护效率极低。
- 方案2(枚举+分支判断):比方案1省事但仍有明显缺陷,当作物种类变多后会产出超长的if-else/switch分支,新增作物时既要修改枚举定义,还要遍历所有用到分支判断的位置修改,漏改就会触发bug,不符合开闭原则。
推荐实现方式
直接定义通用Crop类,把所有作物通用的属性(生长周期、采购价格、基础售卖价格、图片路径等)和行为逻辑(判断成熟、计算当前售价等)都放在这个类里实现,不需要做任何子类继承。
单独维护一套作物配置映射表,程序启动时加载一次即可,需要生成对应作物时直接从配置表取模板初始化实例即可,不用写任何分支判断。
代码示例(C#为例)
public class Crop { // 通用属性 public string CropId { get; set; } public int GrowCycle { get; set; } public int PurchasePrice { get; set; } public int BaseSellPrice { get; set; } public string SpritePath { get; set; } public int CurrentGrowTurn { get; set; } // 通用逻辑统一实现,无需分支 public int GetCurrentSellValue() { // 直接结合市场浮动系数计算即可,不需要按作物类型判断 return BaseSellPrice * StockMarket.GetPriceFluctuation(CropId); } public bool CheckIsRipe() { return CurrentGrowTurn >= GrowCycle; } // 拷贝构造函数,用配置模板生成新实例 public Crop(Crop template) { CropId = template.CropId; GrowCycle = template.GrowCycle; PurchasePrice = template.PurchasePrice; BaseSellPrice = template.BaseSellPrice; SpritePath = template.SpritePath; CurrentGrowTurn = 0; } } // 全局作物配置类,启动时加载一次即可 public static class CropConfigCenter { private static readonly Dictionary<string, Crop> _cropTemplates = new Dictionary<string, Crop>() { { "Wheat", new Crop { CropId = "Wheat", GrowCycle = 3, PurchasePrice = 10, BaseSellPrice = 20, SpritePath = "Assets/Sprites/Crops/Wheat.png" } }, { "Corn", new Crop { CropId = "Corn", GrowCycle = 5, PurchasePrice = 20, BaseSellPrice = 35, SpritePath = "Assets/Sprites/Crops/Corn.png" } }, { "Barley", new Crop { CropId = "Barley", GrowCycle = 4, PurchasePrice = 12, BaseSellPrice = 24, SpritePath = "Assets/Sprites/Crops/Barley.png" } } }; public static Crop GetNewCropInstance(string cropId) { return new Crop(_cropTemplates[cropId]); } }
方案优势
- 零冗余代码,所有公共逻辑仅需实现一次
- 扩展成本极低,新增作物只需要在配置表加一条记录,不需要修改任何现有业务逻辑
- 支持把配置抽成外部JSON/CSV文件,不用改代码就能调整作物数值,方便调整游戏平衡
如果只能在你给出的两个方案里选,优先选方案2,把分支判断改成查表逻辑即可,本质也是往数据驱动的方向靠拢。
内容的提问来源于stack exchange,提问作者ninjajosh5
相关产品推荐
相关产品推荐

