C#依赖与耦合

  总结一下在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());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shiaohan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值