Unity 依赖倒置原则

1.定义

高层模块不应该依赖低层模块,二者都应该依赖其抽象;抽象不应该依赖细节;细节应该依赖抽象。

以抽象为基础搭建起来的架构比以细节为基础搭建起来的架构要稳定的多。 
抽象指的是接口或者抽象类,细节就是具体的实现类,使用接口或者抽象类的目的是制定好规范和契约,而不去涉

及任何具体的操作,把展现细节的任务交给他们的实现类去完成。

2.依赖倒置原则核心思想

依赖倒置原则的核心思想是面向接口编程

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

public interface IReader {

    string GetContent();
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Book : IReader
{   
    public string GetContent()
    {
        return string.Format("从前有一座山,山上有一个和尚。。。");
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewPaper : IReader
{
    public string GetContent()
    {
        return string.Format("苹果今天发布了全面屏的ipad");
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Mother
{
    public void Say(IReader reader)
    {
        Debug.Log("妈妈开始讲故事");
        Debug.Log(reader.GetContent());

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

public class Door : MonoBehaviour {

	// Use this for initialization
	void Start () {
        Mother mother = new Mother();
        mother.Say(new  NewPaper ());
        mother.Say(new Book());
	}

}

3.效果图如下:

参考链接:https://www.cnblogs.com/zhaoqingqing/p/4288454.html#autoid-3-6-0

猜你喜欢

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