4.Unity面向对象-接口隔离原则

接口隔离原则(ISP)指出no client should be forced to depend on methods it does not use(不应强迫任何客户端依赖它不使用的方法)。

换句话说,避免大接口。遵循与单一职责原则相同的想法,即保持类和方法简短。这为你提供了最大的灵活性,保持接口紧凑和聚焦。

想象你正在制作一个具有不同玩家单位的策略游戏。每个单位有不同的属性,如生命值和速度。你可能想要一个接口来保证所有单位实现类似的功能:

复制代码
public interface IUnitStats
{
    public float Health { get; set; }
    public int Defense { get; set; }
    public void Die();
    public void TakeDamage();
    public void RestoreHealth();
    public float MoveSpeed { get; set; }
    public float Acceleration { get; set; }
    public void GoForward();
    public void Reverse();
    public void TurnLeft();
    public void TurnRight();
    public int Strength { get; set; }
    public int Dexterity { get; set; }
    public int Endurance { get; set; }
}

假设你想制作一个可破坏的道具,如可击碎的桶或箱子。这个道具也需要生命值的概念,尽管它不会移动。桶或桶也不会具有游戏中其他单位的许多能力。

将其拆分成几个较小的接口,而不是创建一个给可破坏道具太多方法的接口。然后实现它们的类只会混合和匹配它需要的。

将接口拆分成更小的接口。

复制代码
public interface IMovable
{
    public float MoveSpeed { get; set; }
    public float Acceleration { get; set; }
    public void GoForward();
    public void Reverse();
    public void TurnLeft();
    public void TurnRight();
}

public interface IDamageable
{
    public float Health { get; set; }
    public int Defense { get; set; }
    public void Die();
    public void TakeDamage();
    public void RestoreHealth();
}

public interface IUnitStats
{
    public int Strength { get; set; }
    public int Dexterity { get; set; }
    public int Endurance { get; set; }
}

你还可以为爆炸桶添加一个IExplodable接口:

复制代码
public interface IExplodable
{
    public float Mass { get; set; }
    public float ExplosiveForce { get; set; }
    public float FuseDelay { get; set; }
    public void Explode();
}

因为一个类可以实现多个接口,你可以将一个敌人单位由IDamageable、IMovable和IUnitStats组成。一个爆炸桶可以使用IDamageable和IExplodable,而不需要其他接口的不必要开销。

复制代码
public class ExplodingBarrel : MonoBehaviour, IDamageable, IExplodable { ... }
public class EnemyUnit : MonoBehaviour, IDamageable, IMovable, IUnitStats { ... }

再次强调,这优先考虑组合而不是继承,类似于里氏替换原则中的示例。接口隔离原则有助于解耦你的系统,使它们更容易修改和重新部署。

相关推荐
zb200641202 小时前
spring security 超详细使用教程(接入springboot、前后端分离)
java·spring boot·spring
啥咕啦呛2 小时前
java打卡学习3:ArrayList扩容机制
java·python·学习
rrrjqy2 小时前
Java基础篇(二)
java·开发语言
Mr.45672 小时前
JDK17+Druid+SpringBoot3+ShardingSphere5 多表分库分表完整实践(MySQL+PostgreSQL)
java·数据库·spring boot·mysql·postgresql
tsyjjOvO2 小时前
Spring Boot 入门
java·spring boot·后端
RuoyiOffice2 小时前
SpringBoot+Vue3+Uniapp实现PC+APP双端考勤打卡设计:GPS围栏/内网双模打卡、节假日方案、定时预生成——附数据结构和核心源码讲解
java·spring·小程序·uni-app·vue·产品运营·ruoyi
StackNoOverflow2 小时前
Spring Boot 核心知识点总结
java·spring boot·后端
世界哪有真情2 小时前
使用 Arthas 精准排查 SpringBoot 多模块项目中未使用的类(安全清理无用代码)
java·后端
softbangong2 小时前
816-批量将图片分别转为pdf,文件夹下所有图片转为一个pdf
java·服务器·pdf·图片处理·图片转pdf·pdf工具·批量转换