**
单一原则
**
图片
1.需要如下几个demo傻瓜式类,如图。
上代码
2.首先想到声明一个公共类Animal,有吃、呼吸的行为。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 单一原则
{
/// <summary>
/// 一个类只负责一件事
/// </summary>
public class Animal
{
private string _name = null;
public Animal(string name)
{
this._name = name;
}
public void breath()
{
Console.WriteLine("{0} 呼吸空气",this._name);
}
}
}
发现,不同的动物其行为虽有相同,但具体会有差异。比如:
鸡 吃米,呼吸空气。鱼 吃水草,呼吸水。显然这个Animal不满足,需要增加判断逻辑去实现。
拆分类
3.鱼类,行为吃、呼吸。但是吃的是水草,呼吸水。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 单一原则
{
public class Fish
{
//private string _name = null;
public Fish(string name):base(name)//继承父类的属性
{
this._name = name;
}
public void breath()//override关键字去,体现抽象类的行为实体breath()
{
Console.WriteLine("{0} 呼吸水", this._name);
}
public void Eat()//override关键字去,体现抽象类的行为实体breath()
{
Console.WriteLine("{0} 吃水草", this._name);
}
}
}
4.鸡类,行为吃、呼吸。但是吃的是米,呼吸空气。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 单一原则
{
public class Chicken
{
//private string _name = null;
public Chicken(string name):base(name)
{
this._name = name;
}
public void breath()//override关键字去,体现抽象类的行为实体breath()
{
Console.WriteLine("{0} 呼吸空气", this._name);
}
public void Eat()//override关键字去,体现抽象类的行为实体breath()
{
Console.WriteLine("{0} 吃米", this._name);
}
}
}
到这里发现,有代码重复,行为有相同指出。于是将其Animal类进行抽象。
5.鱼和鸡,有公有的行为,呼吸,吃等。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 单一原则
{
public abstract class AbstractAnimal
{
protected string _name = null;//当前类以及子类可以访问protected
public AbstractAnimal(string name)
{
this._name = name;
}
public abstract void breath();//抽象类下面的行为没有具体行为实体,只声明方法名。在子类上有体现
public abstract void Eat();//子类的共有行为
}
}
6.更改下鸡、鱼类。
展示下鸡,鱼一样。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 单一原则
{
public class Chicken: AbstractAnimal
{
//private string _name = null;
public Chicken(string name):base(name)
{
this._name = name;
}
public override void breath()//override关键字去,体现抽象类的行为实体breath()
{
Console.WriteLine("{0} 呼吸空气", this._name);
}
public override void Eat()//override关键字去,体现抽象类的行为实体breath()
{
Console.WriteLine("{0} 吃米", this._name);
}
}
}
7.调用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 单一原则
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("***************************************");
Chicken c1 = new Chicken("鸡鸡");
c1.breath();
c1.Eat();
Console.WriteLine("***************************************");
Fish f1 = new Fish("小鲤鱼");
f1.breath();
f1.Eat();
Console.ReadKey();
}
}
}
结果:
2020_07_18 凌晨00:56记。