单一职责原则
单一职责原则(Single Responsibility Principle,SRP)
核心思想:一个类只负责一个功能领域中的相应职责
案例分析:
案例一:
1、实现动物类,拥有跑方法,符合单一职责
class Animal {
constructor(name) {
this.name = name
}
running() {
console.log(`${this.name} is running`)
}
}
const dog = new Animal('dog')
dog.running()
const cat = new Animal('cat')
cat.running()
2、添加需求,拥有游泳方法
-
方法一
class Animal { constructor(name, type) { this.name = name this.type = type } running() { if (this.type == '陆生') { console.log(`${this.name} is running`) } if (this.type == '水生') { console.log(`${this.name} is swimming`) } } } const dog = new Animal('dog', '陆生') dog.running() const fish = new Animal('fish', '水生') fish.running()
违背单一职责原则,running方法需要区分水生还是陆生,添加别的类型时也需要修改running方法。
-
方法二
class Animal { constructor(name) { this.name = name } running() { console.log(`${this.name} is running`) } swimming() { console.log(`${this.name} is swimming`) } } const dog = new Animal('dog') dog.running() const fish = new Animal('fish') fish.swimming()
方法符合单一职责原则,区分了running和swimming,但类不符合单一职责原则。容易出现狗调用swimming的情况。
-
方法三
class TerrestrialAnimal { constructor(name) { this.name = name } running() { console.log(`${this.name} is running`) } } class AquaticAnimal { constructor(name) { this.name = name } swimming() { console.log(`${this.name} is swimming`) } } const dog = new TerrestrialAnimal('dog') dog.running() const fish = new AquaticAnimal('fish') fish.swimming()
根据职责将动物拆分成陆生生物和水生生物,符合单一职责原则。
案例二:
有一个UserManager
类,它负责用户验证、用户数据存储以及向用户发送通知,这违反了单一职责原则。
interface User {
username: string;
email: string;
}
class UserManager {
validateUser(user: User): boolean {
// 用户验证逻辑
return true; // 假设验证总是成功
}
storeUser(user: User): void {
// 用户存储逻辑
console.log(`${user.username} stored in database.`);
}
sendNotification(user: User, message: string): void {
// 发送通知逻辑
console.log(`Notification sent to ${user.username}: ${message}`);
}
createUser(user: User): void {
if (!this.validateUser(user)) {
console.log('User validation failed.');
return;
}
this.storeUser(user);
this.sendNotification(user, 'User created successfully.');
}
}
将UserManager
类的职责拆分为三个类:UserValidator
、UserStorage
、和UserNotifier
,每个类只负责一个功能。
interface User {
username: string;
email: string;
}
class UserValidator {
validate(user: User): boolean {
// 用户验证逻辑
return true; // 假设验证总是成功
}
}
class UserStorage {
store(user: User): void {
// 用户存储逻辑
console.log(`${user.username} stored in database.`);
}
}
class UserNotifier {
send(user: User, message: string): void {
// 发送通知逻辑
console.log(`Notification sent to ${user.username}: ${message}`);
}
}
class UserManager {
private validator = new UserValidator();
private storage = new UserStorage();
private notifier = new UserNotifier();
createUser(user: User): void {
if (!this.validator.validate(user)) {
console.log('User validation failed.');
return;
}
this.storage.store(user);
this.notifier.send(user, 'User created successfully.');
}
}