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} 两脚行走");
        }
    }
}
相关推荐
dax.net3 分钟前
在C#中使用适配器Adapter模式和扩展方法解决面向的对象设计问题
设计模式·c#
小白黑_2161 小时前
设计模式笔记
笔记·设计模式
liang89995 小时前
设计模式之装饰器模式(Decorator)
设计模式·装饰器模式
CocoaAndYy5 小时前
设计模式-适配器模式
设计模式·适配器模式
刷帅耍帅5 小时前
设计模式-适配器模式
设计模式·适配器模式
拥有一颗学徒的心7 小时前
设计模式——命令模式
设计模式·命令模式
拉里小猪的迷弟10 小时前
设计模式-结构型-常用:代理模式、桥接模式、装饰者模式、适配器模式
设计模式·代理模式·桥接模式·适配器模式·装饰器模式
CocoaAndYy12 小时前
设计模式-单例模式
单例模式·设计模式
bobostudio199514 小时前
TypeScript 设计模式之【策略模式】
前端·javascript·设计模式·typescript·策略模式
ok!ko18 小时前
设计模式之原型模式(通俗易懂--代码辅助理解【Java版】)
java·设计模式·原型模式