一个对象应该只包含单一的职责,并且该职责被完整地封装在一个类中.
就一个类而已,应该仅有一个引起它变化的原因
单一职责原则实例:
// 单一职责原则C#001
using System;
using System.Collections.Generic;
using System.Ling;
using System.Text;
namespace 单一职责原则C001
{
public class Animal
{
public void Breathe(string animalName)
{
console.WriteLine(animalName + "呼吸空气");
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal();
myAnimal.Breathe("牛");
myAnimal.Breathe("羊");
myAnimal.Breathe("猫");
}
}
}
// 单一职责原则C#002
using System;
using System.Collections.Generic;
using System.Ling;
using System.Text;
namespace 单一职责原则C002
{
// 陆地生物
public class Terrestrial
{
public void Breathe(string animalName)
{
console.WriteLine(animalName + "呼吸空气");
}
}
// 水生生物
public class Aquatic
{
public void Breathe(string animalName)
{
console.WriteLine(animalName + "在水中呼吸");
}
}
class Program
{
static void Main(string[] args)
{
Terrestrial myTerrestrial = new Terrestrial();
myTerrestrial.Breathe("牛");
myTerrestrial.Breathe("羊");
myTerrestrial.Breathe("猫");
Aquatic myAquatic = new Aquatic();
myAquatic.Breathe("鱼");
}
}
}
// 单一职责原则C#003
using System;
using System.Collections.Generic;
using System.Ling;
using System.Text;
namespace 单一职责原则C003
{
public class Animal
{
public void Breathe(string animalName)
{
if ("鱼".Equals(animalName))
{
Console.WriteLine(animalName + "在水中呼吸");
}
else
{
Console.WriteLine(animalName + "呼吸空气")
}
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal();
myAnimal.Breathe("牛");
myAnimal.Breathe("羊");
myAnimal.Breathe("猫");
myAnimal.Breathe("鱼");
}
}
}
// 单一职责原则C#004
using System;
using System.Collections.Generic;
using System.Ling;
using System.Text;
namespace 单一职责原则C004
{
public class Animal
{
public void Breathe01(string animalName)
{
Console.WriteLine(animalName + "呼吸空气")
}
public void Breathe02(string animalName)
{
Console.WriteLine(animalName + "在水中呼吸");
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal();
myAnimal.Breathe01("牛");
myAnimal.Breathe01("羊");
myAnimal.Breathe01("猫");
myAnimal.Breathe02("鱼");
}
}
}