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} 两脚行走");
        }
    }
}
相关推荐
摘星编程2 小时前
并发设计模式实战系列(3):工作队列
设计模式·并发编程
Pasregret3 小时前
访问者模式:分离数据结构与操作的设计模式
数据结构·设计模式·访问者模式
Aniugel5 小时前
JavaScript高级面试题
javascript·设计模式·面试
不当菜虚困6 小时前
JAVA设计模式——(四)门面模式
java·开发语言·设计模式
Niuguangshuo6 小时前
Python设计模式:MVC模式
python·设计模式·mvc
Lei活在当下6 小时前
【现代 Android APP 架构】01. APP 架构综述
android·设计模式·架构
前端大白话6 小时前
震惊!90%前端工程师都踩过的坑!computed属性vs methods到底该怎么选?一文揭秘高效开发密码
前端·vue.js·设计模式
前端大白话6 小时前
前端必看!figure标签在响应式图片排版中的王炸操作,grid/flex布局实战指南
前端·设计模式·html
ApeAssistant7 小时前
Spring + 设计模式 (十四) 行为型 - 观察者模式
spring·设计模式
ApeAssistant7 小时前
Spring + 设计模式 (十三) 行为型 - 策略模式
spring·设计模式