Unity3D 学习笔记(补充) 里氏转换原则与抽象类

2020-02-27  本文已影响0人  Never肥宅

非常相似的类可以把它概括起来,比如键鼠输入和手柄输入
创建一个新的类IUserInterface,把共有的变量保存进来,然后把原有的键鼠控制类继承这个IUserInterface
此时会出现保护级别的问题


保护级别

把原有的private改成protected,这样的话其子类可以访问,但是别的类不能访问,就可以解决这个问题
将原来程序中的PlayerController类都换成IUserInterface
程序能够继续运行是因为此处符合里氏转换原则,即:
If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T,the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T.(如果对每一个类型为S的对象o1,都有类型为T的对象o2,使得以T定义的所有程序P在所有的对象o1都代换成o2时,程序P的行为没有发生变化,那么类型S是类型T的子类型。)

为了防止这个仅作接口的类IUserInput被误用,加入关键词abstract使其变为抽象类,这样这个类就无法被实例化,只能作为其他类的父类

在有了IUserInterface父类之后,为了让pi能获取所有的IUserInterface
修改原有的
pi = GetComponent<IUserInterface>();

        IUserInterface[] inputs = GetComponents<IUserInterface>();
        foreach(var input in inputs){
            if(input.enabled == true){
                pi = input;
                break;
            }
        }

即可

上一篇下一篇

猜你喜欢

热点阅读