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} 两脚行走");
        }
    }
}
相关推荐
路弥行至13 小时前
【Head First 设计模式】第 2 章:观察者模式 —— 用现代 C++ 重新解读“交互对象的松耦合
c++·经验分享·笔记·观察者模式·设计模式·入门教程·headfirst
YYYing.13 小时前
【设计模式系列 (九) 】装饰器模式
c++·后端·设计模式·装饰器模式·c/c++
沫璃染墨17 小时前
《从零入门Linux系统篇(五十六):线程篇·九——生产者消费者模型:从条件变量到BlockingQueue实现》
linux·服务器·c++·驱动开发·设计模式·架构·系统架构
c萱2 天前
AI产品经理——01基础认知篇
设计模式·prompt·aigc·产品经理·ai编程·gitcode·ai-native
YYYing.2 天前
【设计模式系列 (八) 】组合模式
c++·后端·设计模式·组合模式·c/c++
geovindu2 天前
rust: Composite Pattern
开发语言·后端·设计模式·rust·组合模式
YYYing.2 天前
【设计模式系列 (七) 】桥接模式
c++·后端·设计模式·桥接模式
阿狗童鞋3 天前
设计模式实战指南
设计模式
电子科技圈3 天前
基于车载SerDes和OpenGMSL协议的SoC设计与验证:行业高频问题解析
设计模式·车载系统·软件构建·设计规范
ClinicTech4 天前
高速冷冻离心机的温控系统与安全保护逻辑解析
设计模式·架构·健康医疗·设计语言