C# 设计原则 之 依赖倒置 原则

依赖倒置原则 是程序要依赖于抽象接口,不要依赖于具体实现。简单的说就是要求对抽象进行编程,不要对实现进行编程,这样就降低了客户与实现模块间的耦合。面向接口编程

以歌手 能唱多种 语言的歌曲 作为 例子:

1.1创建歌曲 抽象 类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 依赖倒置.interfaceClass
{
    public interface InterfaceSong
    {
        string Song();
    }
}

1.2中文歌曲 实现 歌曲抽象类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 依赖倒置.interfaceClass;

namespace 依赖倒置.CommonClass
{
    public class ChinaSongClass : InterfaceSong
    {
        public string Song()
        {
            return "中国歌曲";
        }
    }
}

1.3英文歌曲 实现 歌曲抽象类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 依赖倒置.interfaceClass;

namespace 依赖倒置.CommonClass
{
    public class EnglishSongClass : InterfaceSong
    {
        public string Song()
        {
            return "英文歌曲";
        }
    }
}

2 建立歌手类。 依赖倒置 核心就是 为了实现 public void Sing(InterfaceSong interfaceSong) 接口,而不是 去实现具体实现业务。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 依赖倒置.interfaceClass;

namespace 依赖倒置
{
    public class SingerClass
    {
        public void Sing(InterfaceSong interfaceSong)
        {
            Console.WriteLine("xx知名歌手在唱"+interfaceSong.Song());
        }
    }
}

3.代码实现 

using 依赖倒置.CommonClass;

namespace 依赖倒置
{
    internal class Program
    {
        static void Main(string[] args)
        {
            SingerClass singerClass = new SingerClass();
            singerClass.Sing(new ChinaSongClass());
            Console.ReadKey();
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值