总结一下在C#语言中关于抽象类与接口的相关知识,来源B站刘铁猛老师的C#课程:《C#语言入门详解》。
耦合的概念:
高内聚低耦合,是软件工程中的概念,是判断软件设计好坏的标准,主要用于程序的面向对象的设计,主要看类的内聚性是否高,耦合度是否低。目的是使程序模块的可重用性、移植性大大增强。耦合是软件结构中各模块之间相互连接的一种度量,耦合强弱取决于模块间接口的复杂程度、进入或访问一个模块的点以及通过接口的数据。
耦合度低的示例:
class Program
{
static void Main(string[] args)
{
var driver = new Driver(new Car());//实例化Driver类,传入实现IVehicle接口(满足IVehicle契约)的Car的实例
driver.Drive();
System.Console.WriteLine("vehicle message :{0},MaxSpeed is {1},Weight is {2}.",driver._vehicle.Name,driver._vehicle.MaxSpeed,driver._vehicle.Weight);
Console.ReadLine();
}
}
class Driver
{
public IVehicle _vehicle;
//司机驾驶汽车
public Driver(IVehicle vehicle)//构造函数,需要一个IVehicle类型的接口作为参数
{
this._vehicle=vehicle;
}
public void Drive()
{
this._vehicle.Run();
this._vehicle.Stop();
}
}
interface IVehicle//定义接口,制定车辆应满足的规范(契约)
{
public void Run();
public void Stop();
public string Name { get; set; }
public int MaxSpeed { get; set; }
public int Weight { get; set; }
}
class Bicycle : IVehicle//实现IVehicle接口
{
private string name ="Bicycle";
private int maxSpeed = 50;
private int weight = 50;
public string Name { get => name; set => name = value; }
public int Weight { get => weight; set => weight = value; }
public int MaxSpeed { get => maxSpeed; set => maxSpeed = value; }
public void Run()
{
System.Console.WriteLine("Bicycle is running.");
}
public void Stop()
{
System.Console.WriteLine("Stopped...");
}
}
class Car :IVehicle
{
private string name="Car";
private int maxSpeed = 100;
private int weight = 100;
public string Name { get => name; set=> name =value; }
public int Weight { get => weight; set => weight = value; }
public int MaxSpeed { get => maxSpeed; set => maxSpeed = value; }
public void Run()
{
Console.WriteLine("Car is running");
}
public void Stop()
{
System.Console.WriteLine("Stopped...");
}
}
其中,如果驾驶者开的汽车出现故障,更换交通工具,选择骑自行车出行,只需在主方法中将Car替换成Bicycle即可。
var driver = new Driver(new Car());
替换↓↓↓↓
var driver = new Driver(new Bicycle());