设计模式-六大原则

六大原则是设计模式的基石, 是后面所提具体的二十三种设计模式的指导思想

总则: 开放封闭原则

对扩展开放, 对修改封闭

当我们需要添加新的功能时, 可以通过添加新的代码或者模块来实现, 而不需要修改已有的功能模块, 这样可以避免新增的功能影响到原来已经在正常运行的功能

最简单的例子就是函数重载

public void Add(int i)
{
 this.List.Add(i.ToString("N"));
}
public void Add(string i)
{
 this.List.Add(i);
}
public void Add(DateTime time)
{
 this.List.Add(time.ToString("yyyy-MM-dd HH:mm:ss.fff"));
}

当我们需要Add一个新的类型时, 只需要添加一个重载函数即可, 不需要修改已有的Add函数

以下算是一个反例

public void Add(object obj)
{
 if (obj is int i)
 this.List.Add(i.ToString("N"));
 else if (obj is string str)
 this.List.Add(str);
 else if (obj is DateTime time)
 this.List.Add(time.ToString("yyyy-MM-dd HH:mm:ss.fff"));
}

单一职责原则

一个类或者一个方法只有一个职责, 只做一件事情, 只处理一个业务

该原则要求尽可能降低类或方法的复杂度, 提高可读性

下面先来一个简单的反例

public void SetUser(string name, int age, DateTime birthday)
{
 this.name = name;
 this.age = age;
 this.birthday = birthday;
}

假设类中有一个用于设置用户信息的SetUser方法, 可以通过传入三个参数设置三个字段的值

此时这个函数拥有三个职责, 设置name设置age设置birthday

如果我想要单独设置其中的某一个字段, 在现在这种情况下我需要先获取另外两个字段的值, 然后一起传给这个函数

这在使用的时候就非常不方便, 我们可以根据这三个职责将函数进行拆分

public void InitUser(string name, int age, DateTime birthday)
{
 this.name = name;
 this.age = age;
 this.birthday = birthday;
}
public void SetName(string name)
{
 this.name = name;
}
public void SetAge(int age)
{
 this.age = age;
}
public void SetBirthday(DateTime birthday)
{
 this.birthday = birthday;
}

将原来的SetUser改为InitUser, 意为初始化用户信息, 这时候才需要传全部的三个参数

新增了 SetNameSetAgeSetBirthday三个函数, 分别对应 设置name设置age设置birthday这三个职责

里氏替换原则

子类可以替换父类, 并保持父类的功能和特性, 父类可以出现的地方, 都可以使用其子类进行代替

简单来说就是子类的行为应当尽量与父类保持一致

下面来一个简单的反面例子

public class User
{
 protected string name;
 public virtual void SetName(string name)
 {
 this.name = name;
 }
}
public class Student: User
{
 public override void SetName(string name)
 {
 }
}

子类Student重写了SetName方法, 但是这个重写的方法并不会对name字段进行修改, 这无疑就违反了SetName方法的本意, 会让其他人在使用这个方法时会不小心掉进坑里

public class User
{
 protected string name;
 public virtual void SetName(string name)
 {
 this.name = name;
 }
}
public class Student: User
{
 public override void SetName(string name)
 {
 this.name = name;
 }
}

一般来说正常实现这个方法即可

依赖倒置原则

高层模块不应该依赖于低层模块, 二者都应该依赖于抽象, 而不是具体的实现细节

public class Apple
{
 public string Name { get; set; }
 public decimal Price { get; set; }
}
public class Pineapple
{
 public string Name { get; set; }
 public decimal Price { get; set; }
}
public class Pen
{
 public string Name { get; set; }
 public decimal Price { get; set; }
}
public class PenPineappleApplePen
{
 public string Name { get; set; }
 public decimal Price { get; set; }
}
public class User
{
 private List<Apple> Apples { get; set; }
 private List<Pineapple> Pineapples { get; set; }
 private List<Pen> Pens { get; set; }
 private List<PenPineappleApplePen> PenPineappleApplePens { get; set; }
 public void AddApple(Apple good)
 {
 Apples.Add(good);
 }
 public void AddPineapple(Pineapple good)
 {
 Pineapples.Add(good);
 }
 public void AddPen(Pen good)
 {
 Pens.Add(good);
 }
 public void AddPenPineappleApplePen(PenPineappleApplePen good)
 {
 PenPineappleApplePens.Add(good);
 }
 public decimal Count()
 {
 decimal sum = 0;
 sum += Apples.Sum(item => item.Price);
 sum += Pineapples.Sum(item => item.Price);
 sum += Pens.Sum(item => item.Price);
 sum += PenPineappleApplePens.Sum(item => item.Price);
 return sum;
 }
}

上面的User可以购买四种商品, 每种商品都可以添加多个, 加完之后还可以结算价格

但每增加一种商品, User类就需要进行一次修改, 这无疑是非常麻烦且违反开闭原则的

所以我们可以简单地修改一下

public abstract class Good
{
 public string Name { get; set; }
 public decimal Price { get; set; }
}
public class Apple: Good
{
}
public class Pineapple: Good
{
}
public class Pen: Good
{
}
public class PenPineappleApplePen: Good
{
}
public class User
{
 private List<Good> Goods { get; set; }
 public void AddGood(Good good)
 {
 Goods.Add(good);
 }
 public decimal Count()
 {
 decimal sum = Goods.Sum(item => item.Price);
 return sum;
 }
}

User不再依赖具体的商品, 而是依赖抽象的Good, 这样即使具体的商品实现部分有增减修改, 只要抽象的Good没有变化, 就不需要修改现有的模块

接口隔离原则

尽量使用多个专门的接口, 而不是单一的总接口

有时候我们会设计一个"大而全"的接口, 能做很多事情

public interface ICrud<T>
{
 T Get(object id);
 T[] GetList(Condition input);
 void Add(T input);
 void Update(T input);
 void Delete(object id);
}

比如以上的ICrud接口就定义了增删查改总共5个方法, 实现这个接口时需要将这五个方法都实现一遍

但有些情况下我们可能只需要使用查询功能, 这时候就要额外写用不到的三个实现, 会使类变得臃肿, 并且可能会产生副作用

此时就可以考虑按照读写或者增删查改拆分接口, 下面就简单拆分一下

public interface IRead<T>
{
 T Get(object id);
 T[] GetList(Condition input);
}
public interface IWrite<T>
{
 void Add(T input);
 void Update(T input);
 void Delete(object id);
}
public interface ICrud<T>: IRead<T>, IWrite<T>
{
}

拆分之后的ICrud不受影响, 多出来IReadIWrite对应读写, 在只读的情况下我们可以只实现IRead

如果有需要, 可以再根据增删查改进行接口拆分

最少知道原则

一个对象应该对其他对象有尽可能少的了解, 不应该直接与其他对象发生联系

这样做的目的是降低类之间的依赖, 降低耦合, 从而使各个功能模块尽可能独立

public class Teacher
{
 public void GetStudentInfo(Student stu)
 {
 string info = $"学生名称: {stu.Name}; 年龄: {stu.Age}";
 }
}
public class Student
{
 public string Name { get; set; }
 public int Age { get; set; }
}

以上的TeacherGetStudentInfo中尝试获取学生信息拼接而成的字符串, 此时Teacher类对Student类的细节知道的就太多了, 如果Student中添加了新的属性, Teacher中就需要针对这个新加的属性做对应修改, 然而这些新加的属性可能与Teacher本身并没有什么关联, 也不是Teacher需要关心的, 这种高耦合设计会在日后带来很多麻烦

所以我们需要将这些细节屏蔽掉

public class Teacher
{
 public void GetStudentInfo(Student stu)
 {
 string info = stu.GetInfo();
 }
}
public class Student
{
 public string Name { get; set; }
 public int Age { get; set; }
 public DateTime Birthday { get; set; }
 public bool Gender { get; set; }
 public string GetInfo()
 {
 return $"学生名称: {Name}; 年龄: {Age}; 生日: {Birthday.ToString("yyyy-MM-dd")}; 性别: {(Gender ? "男" : "女" )}";
 }
}

像这样把具体的拼接过程放到Student中去实现, 尽可能让Student的更改只局限在Student中, 不影响其公开暴露出来的部分, 只要GetInfo这样的业务没有发生变化, Teacher就不需要进行修改

合成复用原则

尽量使用合成, 而不是通过继承达到复用的目的

程序员对于"复用"是有执念的, 一般来说不喜欢把同一个功能写两遍, 复用代码最简单的方式是 ctrl + cctrl + v, 这种方式虽然简单, 但是也有很多隐患, 比如无法统一修改

另一种比较简单直接的方式是继承, 继承一个现有的类即可获得这个类的功能

public class Gun
{
 public string ProductNo { get; set; }
 public void Shoot()
 {
 Console.WriteLine("啪");
 }
}
public class Police: Gun
{
}

Police通过继承Gun可以复用Shoot方法, 但是与此同时也继承了ProductNo生产批次号, 从业务上来说, Police与生产批次号应该是完全没有关系的, 又不是机械战警

所以这里通过继承来复用就非常不合适了


public class Gun
{
 public string ProductNo { get; set; }
 public void Shoot()
 {
 Console.WriteLine("啪");
 }
}
public class Police
{
 private Gun gun;
 public Police(Gun gun)
 {
 this.gun = gun;
 }
 public void Shoot()
 {
 gun.Shoot();
 }
}

通过组合进行复用可能是一种更合适的方式

作者:崩坏的领航员原文地址:https://www.cnblogs.com/CollapseNav/p/17242593.html

%s 个评论

要回复文章请先登录注册