这是我参与8月更文挑战的第14天,活动详情查看:8月更文挑战

概念:

有且仅有一个原因引起类的变化,也就是一个类只负责一项职责的原则。

方案介绍:

如果在设计之初定义一个类中有多项职责,则应该考虑重新设计将类的粒度进行分解为多个子类,每个子类职责单一。

案例分析:

完整代码地址:CodeSendBox

需求1.0讲解:

在国庆来临之际我们要对优质客户进行促销回馈活动,会员1级的用户8折出售,会员2级的用户7折出售。

代码实现:

  1. export class Product {
  2. // 不同等级的会员享有的折扣不同
  3. sell(member: number, discount: number): void {
  4. if (member === 1) {
  5. console.log("国庆热卖,尊贵的1级会员");
  6. if (discount === 8) {
  7. console.log("8折出售了~");
  8. }
  9. } else if (member === 2) {
  10. console.log("国庆热卖,尊贵的2级会员");
  11. if (discount === 7) {
  12. console.log("7折出售了~");
  13. }
  14. }
  15. }
  16. }
  1. // 两个因素影响产品类;
  2. import { Product } from "./v1";
  3. new Product().sell(1, 8);
  4. new Product().sell(2, 7);

说明:通过上面代码的实现可以看出,我们的商品类在进行出售的时候有两个可变因素,一个是会员等级,另一个是享受折扣。

需求迭代1.1讲解:

在原有的基础上还允许我们的用户使用手中的优惠券进行折上折活动,但是不同的会员等级也是有不同优惠券额度的限制,1级会员最高20元,2级会员最高50元。

代码实现:

  1. export class Product {
  2. // 不同等级的会员在原有折扣的基础上享有不同额度的优惠券使用服务
  3. sell(member: number, discount: number, coupons: number): void {
  4. if (member === 1) {
  5. console.log("国庆热卖,尊贵的1级会员");
  6. if (discount === 8) {
  7. console.log("8折出售了~");
  8. if (coupons <= 20) {
  9. console.log("使用优惠券最高再减20~");
  10. }
  11. }
  12. } else if (member === 2) {
  13. console.log("国庆热卖,尊贵的2级会员");
  14. if (discount === 7) {
  15. console.log("7折出售了~");
  16. if (coupons <= 50) {
  17. console.log("使用优惠券最高再减50~");
  18. }
  19. }
  20. }
  21. }
  22. }
  1. import { Product } from "./v2";
  2. new Product().sell(1, 8, 20);
  3. new Product().sell(2, 7, 50);

功能复盘:

通过第一版的代码实现和第二版的迭代,我们将成功的出售的函数变得更加庞大,按次方法迭代下去,这个方法的复杂度不可估计,每次上线也将变得心惊肉跳的有没有。其实问题的原因就是在设计之初没有考虑好将来的变化为违反了单一职责的原因。

代码重构:

image.png

重新设计后的产品类:
  1. export class Product {
  2. service: IProductService;
  3. constructor(service: IProductService) {
  4. this.service = service;
  5. }
  6. sell() {
  7. this.service.member();
  8. this.service.discount();
  9. this.service.coupons();
  10. }
  11. }

定义产品出售的影响因素接口:
  1. interface IProductService {
  2. member(): void;
  3. discount(): void;
  4. coupons(): void;
  5. }

原来的产品类按会员等级分解为两个会员客户类:

每个等级的客户单独维护与自己紧密相关的因素

  1. export class Level1Customer implements IProductService {
  2. member(): void {
  3. console.log("国庆热卖,尊贵的1级会员");
  4. }
  5. discount(): void {
  6. console.log("8折出售了~");
  7. }
  8. coupons(): void {
  9. console.log("使用优惠券最高再减20~");
  10. }
  11. }
  12. export class Level2Customer implements IProductService {
  13. member(): void {
  14. console.log("国庆热卖,尊贵的2级会员");
  15. }
  16. discount(): void {
  17. console.log("7折出售了~");
  18. }
  19. coupons(): void {
  20. console.log("使用优惠券最高再减50~");
  21. }
  22. }

客户端实现:
  1. import { Product, Level1Customer, Level2Customer } from "./v3";
  2. new Product(new Level1Customer()).sell();
  3. new Product(new Level2Customer()).sell();

再次复盘:

重构后客户端的改造量最少,产品类的拆分导致代码量直线上涨,但是我们的类将变得各司其职,在增加新的售卖方案条件时将对以前版本的侵入变得更少,扩展变得简单,易于维护。