Unity 隔离接口原则

定义

客户端不应该依赖它不需要的接口;一个类对另一个类的依赖应该建立在最小的接口上。 
将臃肿的接口I拆分为独立的几个接口,类A和类C分别与他们需要的接口建立依赖关系。也就是采用接口隔离原则。 
举例来说明接口隔离原则:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface I  {

    void method1();
    void method2();
    void method3();
    void method4();
    void method5();

}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class A  {

    public void depend1(I i)
    {
        i.method1();
    }
    public void depend2(I i)
    {
        i.method2();
    }
    public void depend3(I i)
    {
        i.method3();
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class B : I
{
    public void method1()
    {
        Debug.Log("类B this method1");
    }

    public void method2()
    {
        Debug.Log("类B this method2");
    }

    public void method3()
    {
        Debug.Log("类B this method3");
    }

    public void method4()
    {
        throw new System.NotImplementedException();
    }

    public void method5()
    {
        throw new System.NotImplementedException();
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class C {

    public void depend1(I i)
    {
        i.method1();
    }
    public void depend2(I i)
    {
        i.method4();
    }
    public void depend3(I i)
    {
        i.method5();
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class D : I
{
    public void method1()
    {
        Debug.Log("类A this method1");
    }

    public void method2()
    {
    }

    public void method3()
    {
        throw new System.NotImplementedException();
    }

    public void method4()
    {
        Debug.Log("类A this method4");

    }

    public void method5()
    {
        Debug.Log("类A this method5");

    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InterfaceIsolationDoor : MonoBehaviour {

	// Use this for initialization
	void Start () {
        A a = new A();
        a.depend1(new B());
        a.depend2(new B());
        a.depend3(new B());

        C c = new C();
        c.depend1(new D());
        c.depend2(new D());
        c.depend3(new D());
    }
	

}

效果图如下:

参考链接如下:https://www.cnblogs.com/zhaoqingqing/p/4288454.html#autoid-5-0-0

猜你喜欢

转载自blog.csdn.net/qq_39097425/article/details/83592728