编程语言
首页 > 编程语言> > C#入门详解 刘铁猛 接口、依赖反转、单元测试

C#入门详解 刘铁猛 接口、依赖反转、单元测试

作者:互联网

参考笔记:C#学习笔记(二十三)接口、依赖反转、单元测试
补充:

引入接口降低耦合度。接口就是为了松耦合而生。松耦合最大的好处是:功能的提供方,变得可以被替换,从而降低紧耦合的中紧耦合功能方不能替换所带来的高风险和高成本。
` static void Main(string[] args)
{
var user = new PhoneUser(new RedMi());
user.UserPhone();

        var user2 = new PhoneUser(new VivoPhone());
        user2.UserPhone();
    }



class PhoneUser
{
    private IPhone _phone;
    public PhoneUser(IPhone phone)
    {
        _phone = phone;
    }

    public void UserPhone()
    {
        _phone.Dail();
        _phone.PickUp();
        _phone.Receive();
        _phone.Send();
    }
}




interface IPhone
{
    void Dail();
    void PickUp();
    void Send();
    void Receive();
}



class RedMi : IPhone
{
    public void Dail()
    {
        Console.WriteLine("RedMi calling..");
    }

    public void PickUp()
    {
        Console.WriteLine("Hello!This is Zhangzhang!");
    }

    public void Receive()
    {
        Console.WriteLine("RedMi message ring...");
    }

    public void Send()
    {
        Console.WriteLine("Hello!");
    }
}



class VivoPhone : IPhone
{
    public void Dail()
    {
        Console.WriteLine("Vivo calling..");
    }

    public void PickUp()
    {
        Console.WriteLine("Hello!This is Zhangzhang!");
    }

    public void Receive()
    {
        Console.WriteLine("Vivo message ring...");
    }

    public void Send()
    {
        Console.WriteLine("Hello!");
    }
}

}
`

用一个例子来观察一下 接口、解耦,依赖倒置原则,是怎么被单元测试应用的。

生产电扇的厂家,设计电扇,高电流转的快,低电流转的慢,一般电扇都有电流保护的功能,电流过大断开或者警告功能。

先紧耦合,再分开,单元测试。(此处没有写进行单元测试的代码,有时间再学习、补上)

`
static void Main(string[] args)
{
var fan = new DeskFan(new PowerSupply());
Console.WriteLine(fan.Work());
}

interface IPowerSupply
{
    int GetPower();

}


class PowerSupply : IPowerSupply
{
    public int GetPower()
    {
        return 110;   //测试的数值在这里!!!!!!

//return 220; //会给警告
}

}

class DeskFan //台式电扇
{
    private IPowerSupply _powerSupply;
    public DeskFan(IPowerSupply powerSupply)
    {
        _powerSupply = powerSupply;
    }

    public string Work()
    {
        int power = _powerSupply.GetPower();

        if (power <= 0)
        {
            return "won't worl";
        }
        else if (power < 100)
        {
            return "Slow";
        }
        else if (power < 200)
        {
            return "Work fine ";
        }
        else { return "Waring!"; }

    }


}

`

标签:刘铁猛,Console,C#,void,单元测试,phone,WriteLine,new,public
来源: https://www.cnblogs.com/MinervaZhang/p/16419434.html