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} 两脚行走");
        }
    }
}
相关推荐
Charles_go1 天前
C#中级39、什么是依赖注入设计模式
java·设计模式·c#
ZHE|张恒1 天前
设计模式(八)组合模式 — 以树结构统一管理对象层级
java·设计模式·组合模式
明洞日记1 天前
【设计模式手册011】享元模式 - 共享细粒度对象的高效之道
java·设计模式·享元模式
帅中的小灰灰1 天前
C++编程观察者设计模式
数据库·c++·设计模式
阿波罗尼亚1 天前
Head First设计模式(六) 设计原则 命令模式
设计模式·命令模式
canonical_entropy1 天前
模型驱动架构的数学内核:统一生成与演化的 Y = F(X) ⊕ Delta 不变式
数学·设计模式·架构
小毛驴8501 天前
软件设计模式-代理模式
设计模式·系统安全·代理模式
雨中飘荡的记忆2 天前
工厂模式详解
设计模式
Charles_go2 天前
C#42、什么是建造者设计模式
设计模式
烤麻辣烫2 天前
23种设计模式(新手)-3接口隔离原则
java·开发语言·学习·设计模式·intellij-idea