设计模式之单一职责原则

2021-09-13  本文已影响0人  Matsn

设计模式6大设计原则之单一职责原则

单一职则原则(SRP:Single Responsibility Principle)

一个类只负责一项职责。实现高内聚,低耦合的指导方针。

    public class Animal
    {
        private string _Name = string.Empty;

        public Animal(string name)
        {
            this._Name = name;
        }
        
        //职责不单一: 更改其中一种,会导致所有的都会一起更改,不合理
        public void Breathe()
        {
            if(this._Name == "鸡")
                Console.WriteLine(this._Name + "用肺呼吸氧气");
            else if(this._Name == "鱼")
                Console.WriteLine(this._Name + "用腮呼吸氧气");
            else if(this._Name == "蚯蚓")
                Console.WriteLine(this._Name + "通过体表的粘液交换氧气来呼吸");
            else if(this._Name == "植物")
                Console.WriteLine(this._Name + "通过光合作用来转化二氧化碳来呼吸");
            else
                Console.WriteLine("不支持的物种:" + this._Name);
        }
    }
    new Animal("鸡").Breathe();

    new Animal("鱼").Breathe();

    new Animal("蚯蚓").Breathe();

    new Animal("植物").Breathe();

上面的一个类内,即包含了鸡、鱼、蚯蚓、植物的呼吸方法,明显违反了单一职责原则,按单一职责原则修改后,代码如下:

  public abstract class AbsAnimal
  {
        protected string _Name;

        protected AbsAnimal(string name)
        {
            this._Name = name;
        }

        public abstract void Breathe();
  }

    public class Chicken : AbsAnimal
    {
        public Chicken() : base("鸡") { }

        public override void Breathe()
        {
            Console.WriteLine(this._Name + "用肺呼吸氧气");
        }
    }

    public class Fish : AbsAnimal
    {
        public Fish(string name) : base("鱼") { }

        public override void Breathe()
        {
            Console.WriteLine(this._Name + "用腮呼吸氧气");
        }
    }

    public class EarthWorm : AbsAnimal
    {
        public EarthWorm() : base("蚯蚓") { }

        public override void Breathe()
        {
           Console.WriteLine(this._Name + "通过体表的粘液交换氧气来呼吸");
        }
    }

    public class Plants : AbsAnimal
    {
        public Plants() : base("植物") { }

        public override void Breathe()
        {
            Console.WriteLine(this._Name + "通过光合作用来转化二氧化碳来呼吸");
        }
    }

    AbsAnimal animal = new Chicken();
    animal.Breathe();

    animal = new Fish();
    animal.Breathe();

    animal = new EarthWorm();
    animal.Breathe();

    animal = new Plants();
    animal.Breathe();

优点####:

  1. 降低类的复杂度,一个类只负责一项职责
  2. 提高类的可读性和系统的可维护性
  3. 降低变更引起的风险,修改一个功能时,降低对其它功能的影响

缺点####:

  1. 拆多了零碎,不好管理,不好使用,成本高
上一篇 下一篇

猜你喜欢

热点阅读