C#设计模式六大原则之单一职责原则

单一职责原则(Single Responsibility Principle)

单一职责原则简单来说就是一个类只负责一项职责,一个类只负责一个功能领域中的相应职责。也就是实现高内聚、低耦合。单一职责原则能使用代码阅读简单,易于维护;扩展升级,减少修改,直接增加类;方便代码重用的。

例如,

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            {
                Animal animal = new AnimalChicken("鸡");
                animal.Eat();
                animal.Move();
            }
            {
                Animal animal = new AnimalCow("牛");
                animal.Eat();
                animal.Move();
            }
            Console.ReadKey();
        }
    }
   public abstract class Animal
    {
        protected string _Name = null;
        public Animal(string name)
        {
            this._Name = name;
        }
        public abstract void Eat();
        //{
        //    if (this._Name.Equals("鸡"))
        //    {
        //    Console.WriteLine($"{this._Name} 吃玉米");
        //}
        //    else if (this._Name.Equals("牛"))
        //    {
        //    Console.WriteLine($"{this._Name} 吃草");
        //}
        。。
        //}
        public abstract void Move();
        //if (this._Name.Equals("鸡"))
        //    {
        //    Console.WriteLine($"{this._Name} 两脚行走");
        //}
        //    else if (this._Name.Equals("牛"))
        //    {
        //    Console.WriteLine($"{this._Name} 四脚行走");
        //}
    }
   public class AnimalCow : Animal
    {
        public AnimalCow(string name) : base(name)
        {
        }
        public override void Eat()
        {
            Console.WriteLine($"{this._Name} 吃草");
        }
        public override void Move()
        {
            Console.WriteLine($"{this._Name} 四脚行走");
        }
    }
   public class AnimalChicken : Animal
    {
        public AnimalChicken(string name) : base(name)
        {
        }
        public override void Eat()
        {
            Console.WriteLine($"{this._Name} 吃玉米");
        }
        public override void Move()
        {
            Console.WriteLine($"{this._Name} 两脚行走");
        }
    }
}
相关推荐
静水流深_沧海一粟11 小时前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder11 小时前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室18 小时前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦2 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo5 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4965 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃5 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式
驴儿响叮当20105 天前
设计模式之状态模式
设计模式·状态模式
电子科技圈5 天前
XMOS推动智能音频等媒体处理技术从嵌入式系统转向全新边缘计算
人工智能·mcu·物联网·设计模式·音视频·边缘计算·iot
徐先生 @_@|||5 天前
安装依赖三方exe/msi的软件设计模式
设计模式