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!"; }
}
}

`

posted @   专心Coding的程侠  阅读(267)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示