【程序设计】6大设计原则之单一职责

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

概念:

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

方案介绍:

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

案例分析:

完整代码地址:CodeSendBox

需求1.0讲解:

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

代码实现:

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

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

需求迭代1.1讲解:

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

代码实现:

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

功能复盘:

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

代码重构:

image.png

重新设计后的产品类:
export class Product {
service: IProductService;
constructor(service: IProductService) {
this.service = service;
}
sell() {
this.service.member();
this.service.discount();
this.service.coupons();
}
}
定义产品出售的影响因素接口:
interface IProductService {
member(): void;
discount(): void;
coupons(): void;
}
原来的产品类按会员等级分解为两个会员客户类:

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

export class Level1Customer implements IProductService {
member(): void {
console.log("国庆热卖,尊贵的1级会员");
}
discount(): void {
console.log("8折出售了~");
}
coupons(): void {
console.log("使用优惠券最高再减20~");
}
}
export class Level2Customer implements IProductService {
member(): void {
console.log("国庆热卖,尊贵的2级会员");
}
discount(): void {
console.log("7折出售了~");
}
coupons(): void {
console.log("使用优惠券最高再减50~");
}
}
客户端实现:
import { Product, Level1Customer, Level2Customer } from "./v3";
new Product(new Level1Customer()).sell();
new Product(new Level2Customer()).sell();
再次复盘:

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

posted @   前端小鑫同学  阅读(7)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示