
solid 原则是一组指导原则,可帮助软件开发人员设计健壮、可扩展且可维护的系统。这些原则由 robert c. martin(bob 叔叔)提出,对于面向对象编程创建灵活且可重用的代码至关重要。
在这篇文章中,我们将深入研究每个 solid 原则,解释其目的,并提供 java 示例来演示其应用程序。
定义:一个类应该只有一个改变的理由。这意味着一个类应该只有一项工作或职责。
当一个类具有多个职责时,对一项职责的更改可能会影响或破坏代码的其他部分。通过遵守 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 管理数据库操作。每个类都有一个职责,使代码更干净、更模块化。
定义:类应该对扩展开放,但对修改关闭。这意味着您应该能够在不更改现有代码的情况下添加新功能。
当您修改现有代码时,您有引入错误的风险。 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 接口的新类。
定义:子类型必须可以替换其基本类型,而不改变程序的正确性。
使用多态性时,违反 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 时都能正确运行。
定义:不应强迫客户端实现他们不使用的接口。相反,创建更小、更具体的界面。
大型接口强制实现类包含它们不需要的方法。这会导致代码臃肿和不必要的依赖关系。
// 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 接口,避免了不必要的方法。
定义:高层模块不应该依赖于低层模块。两者都应该依赖于抽象。
对具体实现的直接依赖使代码变得僵化且难以测试。 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 原则是创建可维护、可扩展且强大的软件的强大工具。快速回顾一下:
通过应用这些原则,您的代码将更容易理解、测试并适应不断变化的需求。从小处开始,根据需要进行重构,并逐渐将这些原则融入到您的开发过程中!
以上就是理解软件设计中的 SOLID 原则的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号