理解软件设计中的 SOLID 原则
来源:dev.to
时间:2024-11-26 19:07:00 383浏览 收藏
在文章实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《理解软件设计中的 SOLID 原则》,聊聊,希望可以帮助到正在努力赚钱的你。

solid 原则是一组指导原则,可帮助软件开发人员设计健壮、可扩展且可维护的系统。这些原则由 robert c. martin(bob 叔叔)提出,对于面向对象编程创建灵活且可重用的代码至关重要。
在这篇文章中,我们将深入研究每个 solid 原则,解释其目的,并提供 java 示例来演示其应用程序。
1.单一职责原则(srp)
定义:一个类应该只有一个改变的理由。这意味着一个类应该只有一项工作或职责。
为什么建议零售价很重要
当一个类具有多个职责时,对一项职责的更改可能会影响或破坏代码的其他部分。通过遵守 srp,我们确保了更好的可维护性和可测试性。
例子
// violating srp: a class that handles both user authentication and database operations.
class usermanager {
public void authenticateuser(string username, string password) {
// authentication logic
}
public void saveusertodatabase(user user) {
// database logic
}
}
// following srp: separate responsibilities into distinct classes.
class authservice {
public void authenticateuser(string username, string password) {
// authentication logic
}
}
class userrepository {
public void saveusertodatabase(user user) {
// database logic
}
}
在此示例中,authservice 处理身份验证,userrepository 管理数据库操作。每个类都有一个职责,使代码更干净、更模块化。
2. 开闭原理(ocp)
定义:类应该对扩展开放,但对修改关闭。这意味着您应该能够在不更改现有代码的情况下添加新功能。
为什么 ocp 很重要
当您修改现有代码时,您有引入错误的风险。 ocp 通过继承或组合来促进功能扩展,而不是改变原始实现。
例子
// violating ocp: adding a new discount type requires modifying the existing code.
class discountcalculator {
public double calculatediscount(string discounttype, double amount) {
if ("newyear".equals(discounttype)) {
return amount * 0.10;
} else if ("blackfriday".equals(discounttype)) {
return amount * 0.20;
}
return 0;
}
}
// following ocp: use polymorphism to add new discount types without changing existing code.
interface discount {
double apply(double amount);
}
class newyeardiscount implements discount {
public double apply(double amount) {
return amount * 0.10;
}
}
class blackfridaydiscount implements discount {
public double apply(double amount) {
return amount * 0.20;
}
}
class discountcalculator {
public double calculatediscount(discount discount, double amount) {
return discount.apply(amount);
}
}
现在,添加新的折扣类型只需创建一个实现 discount 接口的新类。
3.里氏替换原理(lsp)
定义:子类型必须可以替换其基本类型,而不改变程序的正确性。
为什么 lsp 很重要
使用多态性时,违反 lsp 可能会导致意外的行为和错误。派生类必须遵守其基类定义的契约。
例子
// violating lsp: a subclass changes the behavior of the parent class in an unexpected way.
class bird {
public void fly() {
system.out.println("flying...");
}
}
class penguin extends bird {
@override
public void fly() {
throw new unsupportedoperationexception("penguins can't fly!");
}
}
// following lsp: refactor the hierarchy to honor substitutability.
abstract class bird {
public abstract void move();
}
class flyingbird extends bird {
public void move() {
system.out.println("flying...");
}
}
class penguin extends bird {
public void move() {
system.out.println("swimming...");
}
}
通过重新设计层次结构,flyingbird 和 penguin 在替换 bird 时都能正确运行。
4. 接口隔离原则(isp)
定义:不应强迫客户端实现他们不使用的接口。相反,创建更小、更具体的界面。
为什么 isp 很重要
大型接口强制实现类包含它们不需要的方法。这会导致代码臃肿和不必要的依赖关系。
例子
// violating isp: a large interface with unrelated methods.
interface worker {
void work();
void eat();
}
class robot implements worker {
public void work() {
system.out.println("working...");
}
public void eat() {
// robots don't eat, but they're forced to implement this method.
throw new unsupportedoperationexception("robots don't eat!");
}
}
// following isp: split the interface into smaller, focused interfaces.
interface workable {
void work();
}
interface eatable {
void eat();
}
class robot implements workable {
public void work() {
system.out.println("working...");
}
}
class human implements workable, eatable {
public void work() {
system.out.println("working...");
}
public void eat() {
system.out.println("eating...");
}
}
现在,robot 只实现了 workable 接口,避免了不必要的方法。
5. 依赖倒置原则(dip)
定义:高层模块不应该依赖于低层模块。两者都应该依赖于抽象。
为什么 dip 很重要
对具体实现的直接依赖使代码变得僵化且难以测试。 dip 提倡使用抽象(接口)来解耦组件。
例子
// Violating DIP: High-level class depends on a low-level implementation.
class MySQLDatabase {
public void connect() {
System.out.println("Connecting to MySQL...");
}
}
class UserService {
private MySQLDatabase database;
public UserService() {
this.database = new MySQLDatabase(); // Tight coupling
}
public void performDatabaseOperation() {
database.connect();
}
}
// Following DIP: High-level class depends on an abstraction.
interface Database {
void connect();
}
class MySQLDatabase implements Database {
public void connect() {
System.out.println("Connecting to MySQL...");
}
}
class UserService {
private Database database;
public UserService(Database database) {
this.database = database; // Depend on abstraction
}
public void performDatabaseOperation() {
database.connect();
}
}
// Usage
Database db = new MySQLDatabase();
UserService userService = new UserService(db);
userService.performDatabaseOperation();
通过这种设计,您可以轻松地交换数据库实现(例如 postgresql、mongodb),而无需修改 userservice 类。
结论
solid 原则是创建可维护、可扩展且强大的软件的强大工具。快速回顾一下:
- srp:一个班级,一种责任。
- ocp:在不修改现有代码的情况下扩展功能。
- lsp:子类型必须可替换其基本类型。
- isp:更喜欢较小的、集中的界面。
- dip:依赖于抽象,而不是具体实现。
通过应用这些原则,您的代码将更容易理解、测试并适应不断变化的需求。从小处开始,根据需要进行重构,并逐渐将这些原则融入到您的开发过程中!
今天关于《理解软件设计中的 SOLID 原则》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
161 收藏
-
258 收藏
-
490 收藏
-
427 收藏
-
394 收藏
-
249 收藏
-
269 收藏
-
404 收藏
-
464 收藏
-
492 收藏
-
244 收藏
-
180 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习