亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
2. Open/Closed Principle (OCP)
3. Liskov Substitution Principle (LSP)
4. Interface Segregation Principle (ISP)
5. Dependency Inversion Principle (DIP)
Final Thoughts
首頁(yè) Java java教程 為Java開(kāi)發(fā)人員解釋的堅(jiān)實(shí)原則

為Java開(kāi)發(fā)人員解釋的堅(jiān)實(shí)原則

Jul 26, 2025 am 05:16 AM
java SOLID原則

單一職責(zé)原則(SRP)要求一個(gè)類(lèi)只負(fù)責(zé)一項(xiàng)功能,如將訂單處理中的保存和郵件發(fā)送分離;2. 開(kāi)閉原則(OCP)要求對(duì)擴(kuò)展開(kāi)放、對(duì)修改關(guān)閉,如通過(guò)Shape接口實(shí)現(xiàn)新增圖形無(wú)需修改計(jì)算器;3. 里氏替換原則(LSP)要求子類(lèi)能替換父類(lèi)而不破壞程序,如用獨(dú)立類(lèi)避免正方形繼承矩形導(dǎo)致的行為異常;4. 接口隔離原則(ISP)要求客戶端不應(yīng)依賴不需要的接口,如拆分多功能設(shè)備接口為獨(dú)立的打印、掃描、傳真接口;5. 依賴倒置原則(DIP)要求高層模塊不依賴低層模塊,兩者都依賴抽象,如OrderService依賴Database接口而非具體實(shí)現(xiàn)。這五個(gè)原則共同提升Java代碼的可維護(hù)性、可擴(kuò)展性和可測(cè)試性。

The SOLID Principles Explained for Java Developers

The SOLID principles are a set of five design principles intended to make software designs more understandable, flexible, and maintainable—especially in object-oriented programming. For Java developers, applying SOLID helps build systems that are easier to extend, test, and refactor. Let's break down each principle with practical Java examples and clear explanations.

The SOLID Principles Explained for Java Developers

1. Single Responsibility Principle (SRP)

A class should have only one reason to change.

In other words, a class should be responsible for a single part of the application's functionality. If a class handles multiple tasks, changing one might break the other.

The SOLID Principles Explained for Java Developers

Example (Violation):

 public class OrderProcessor {
    public void processOrder(Order order) {
        // Save order to database
        saveToDatabase(order);

        // Send confirmation email
        sendEmail(order.getCustomerEmail());
    }

    private void saveToDatabase(Order order) { /* ... */ }
    private void sendEmail(String email) { /* ... */ }
}

Here, OrderProcessor handles both data persistence and communication—two responsibilities.

The SOLID Principles Explained for Java Developers

Refactored (SRP Compliant):

 public class OrderRepository {
    public void save(Order order) { /* ... */ }
}

public class EmailService {
    public void sendConfirmation(String email) { /* ... */ }
}

public class OrderProcessor {
    private OrderRepository repository;
    private EmailService emailService;

    public void processOrder(Order order) {
        repository.save(order);
        emailService.sendConfirmation(order.getCustomerEmail());
    }
}

Now each class has a single job. Changes to email logic won't affect data saving.


2. Open/Closed Principle (OCP)

Software entities should be open for extension, but closed for modification.

You should be able to add new functionality without changing existing code.

Example (Violation):

 public class AreaCalculator {
    public double calculateArea(List<Object> shapes) {
        double total = 0;
        for (Object shape : shapes) {
            if (shape instanceof Circle) {
                Circle c = (Circle) shape;
                total = Math.PI * c.radius * c.radius;
            } else if (shape instanceof Rectangle) {
                Rectangle r = (Rectangle) shape;
                total = r.width * r.height;
            }
        }
        return total;
    }
}

Every time you add a new shape, you must modify this method.

Refactored (OCP Compliant):

 public interface Shape {
    double area();
}

public class Circle implements Shape {
    private double radius;
    public double area() { return Math.PI * radius * radius; }
}

public class Rectangle implements Shape {
    private double width, height;
    public double area() { return width * height; }
}

public class AreaCalculator {
    public double calculateArea(List<Shape> shapes) {
        return shapes.stream()
                     .mapToDouble(Shape::area)
                     .sum();
    }
}

Now you can add new shapes (eg, Triangle) without touching AreaCalculator .


3. Liskov Substitution Principle (LSP)

Subtypes must be substitutable for their base types without altering the correctness of the program.

If a class inherits from another, it should not break the expected behavior.

Example (Violation):

 public class Rectangle {
    protected int width, height;

    public void setWidth(int width) { this.width = width; }
    public void setHeight(int height) { this.height = height; }

    public int getArea() { return width * height; }
}

public class Square extends Rectangle {
    @Override
    public void setWidth(int width) {
        super.setWidth(width);
        super.setHeight(width);
    }

    @Override
    public void setHeight(int height) {
        super.setHeight(height);
        super.setWidth(height);
    }
}

Now, if a method expects a Rectangle and sets width and height independently, using a Square breaks that assumption.

Better Approach: Avoid inheritance when behavior contracts are violated. Use composition or separate hierarchies.

 public interface Shape {
    int area();
}

public class Rectangle implements Shape {
    private int width, height;
    // setters and area()
}

public class Square implements Shape {
    private int side;
    // area = side * side
}

Now, no misleading inheritance. LSP is preserved.


4. Interface Segregation Principle (ISP)

Clients should not be forced to depend on interfaces they do not use.

Big, monolithic interfaces make classes implement methods they don't need.

Example (Violation):

 public interface Machine {
    void print();
    void scan();
    void fax();
}

public class OldPrinter implements Machine {
    public void print() { System.out.println("Printing"); }
    public void scan() { throw new UnsupportedOperationException(); }
    public void fax() { throw new UnsupportedOperationException(); }
}

OldPrinter is forced to implement irrelevant methods.

Refactored (ISP Compliant):

 public interface Printer {
    void print();
}

public interface Scanner {
    void scan();
}

public interface FaxMachine {
    void fax();
}

public class OldPrinter implements Printer {
    public void print() { System.out.println("Printing"); }
}

public class MultiFunctionDevice implements Printer, Scanner, FaxMachine {
    public void print() { /* ... */ }
    public void scan() { /* ... */ }
    public void fax() { /* ... */ }
}

Now, classes implement only what they support.


5. Dependency Inversion Principle (DIP)

High-level modules should not depend on low-level modules. Both should depend on abstractions.

Also: Abstractions should not depend on details. Details should depend on abstractions.

This enables loose coupling and easier testing.

Example (Violation):

 public class OrderService {
    private MySQLDatabase database = new MySQLDatabase();

    public void saveOrder(Order order) {
        database.save(order);
    }
}

OrderService is tightly coupled to MySQLDatabase . Hard to test or switch databases.

Refactored (DIP Compliant):

 public interface Database {
    void save(Order order);
}

public class MySQLDatabase implements Database {
    public void save(Order order) { /* ... */ }
}

public class OrderService {
    private Database database;

    public OrderService(Database database) {
        this.database = database;
    }

    public void saveOrder(Order order) {
        database.save(order);
    }
}

Now OrderService depends on the Database interface. You can inject any implementation (MySQL, PostgreSQL, Mock, etc.).

Used with dependency injection frameworks (like Spring), this becomes even more powerful.


Final Thoughts

SOLID principles aren't rigid rules—they're guidelines to help you write cleaner, more maintainable Java code. Applying them early can save you from technical debt later.

  • SRP : One job per class.
  • OCP : Extend, don't modify.
  • LSP : Subclasses shouldn't surprise users.
  • ISP : Small, focused interfaces.
  • DIP : Depend on abstractions, not concretions.

They might feel like overkill at first, especially in small projects. But as your codebase grows, these principles become essential tools for managing complexity.

Basically, if your Java classes are hard to test, change, or reuse—chances are, one or more SOLID principles are being violated.

以上是為Java開(kāi)發(fā)人員解釋的堅(jiān)實(shí)原則的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請(qǐng)聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開(kāi)發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)程式碼編輯軟體(SublimeText3)

熱門(mén)話題

Laravel 教程
1597
29
PHP教程
1488
72
VSCODE設(shè)置。 JSON位置 VSCODE設(shè)置。 JSON位置 Aug 01, 2025 am 06:12 AM

settings.json文件位於用戶級(jí)或工作區(qū)級(jí)路徑,用於自定義VSCode設(shè)置。 1.用戶級(jí)路徑:Windows為C:\Users\\AppData\Roaming\Code\User\settings.json,macOS為/Users//Library/ApplicationSupport/Code/User/settings.json,Linux為/home//.config/Code/User/settings.json;2.工作區(qū)級(jí)路徑:項(xiàng)目根目錄下的.vscode/settings

如何使用JDBC處理Java的交易? 如何使用JDBC處理Java的交易? Aug 02, 2025 pm 12:29 PM

要正確處理JDBC事務(wù),必須先關(guān)閉自動(dòng)提交模式,再執(zhí)行多個(gè)操作,最後根據(jù)結(jié)果提交或回滾;1.調(diào)用conn.setAutoCommit(false)以開(kāi)始事務(wù);2.執(zhí)行多個(gè)SQL操作,如INSERT和UPDATE;3.若所有操作成功則調(diào)用conn.commit(),若發(fā)生異常則調(diào)用conn.rollback()確保數(shù)據(jù)一致性;同時(shí)應(yīng)使用try-with-resources管理資源,妥善處理異常並關(guān)閉連接,避免連接洩漏;此外建議使用連接池、設(shè)置保存點(diǎn)實(shí)現(xiàn)部分回滾,並保持事務(wù)盡可能短以提升性能。

Python Itertools組合示例 Python Itertools組合示例 Jul 31, 2025 am 09:53 AM

itertools.combinations用於生成從可迭代對(duì)像中選取指定數(shù)量元素的所有不重複組合(順序無(wú)關(guān)),其用法包括:1.從列表中選2個(gè)元素組合,如('A','B')、('A','C')等,避免重複順序;2.對(duì)字符串取3個(gè)字符組合,如"abc"、"abd",適用於子序列生成;3.求兩數(shù)之和等於目標(biāo)值的組合,如1 5=6,簡(jiǎn)化雙重循環(huán)邏輯;組合與排列的區(qū)別在於順序是否重要,combinations視AB與BA為相同,而permutations視為不同;

在Java的掌握依賴注入春季和Guice 在Java的掌握依賴注入春季和Guice Aug 01, 2025 am 05:53 AM

依賴性(di)IsadesignpatternwhereObjectsReceivedenciesenciesExtern上,推廣looseSecouplingAndEaseerTestingThroughConstructor,setter,orfieldInjection.2.springfraMefringframeWorkSannotationsLikeLikeLike@component@component,@component,@service,@autowiredwithjava-service和@autowiredwithjava-ligatiredwithjava-lase-lightike

Python Pytest夾具示例 Python Pytest夾具示例 Jul 31, 2025 am 09:35 AM

fixture是用於為測(cè)試提供預(yù)設(shè)環(huán)境或數(shù)據(jù)的函數(shù),1.使用@pytest.fixture裝飾器定義fixture;2.在測(cè)試函數(shù)中以參數(shù)形式註入fixture;3.yield之前執(zhí)行setup,之後執(zhí)行teardown;4.通過(guò)scope參數(shù)控製作用域,如function、module等;5.將共用fixture放在conftest.py中實(shí)現(xiàn)跨文件共享,從而提升測(cè)試的可維護(hù)性和復(fù)用性。

故障排除常見(jiàn)的java`ofmemoryError`場(chǎng)景'' 故障排除常見(jiàn)的java`ofmemoryError`場(chǎng)景'' Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError:Javaheapspace表示堆內(nèi)存不足,需檢查大對(duì)象處理、內(nèi)存洩漏及堆設(shè)置,通過(guò)堆轉(zhuǎn)儲(chǔ)分析工具定位並優(yōu)化代碼;2.Metaspace錯(cuò)誤因類(lèi)元數(shù)據(jù)過(guò)多,常見(jiàn)於動(dòng)態(tài)類(lèi)生成或熱部署,應(yīng)限制MaxMetaspaceSize並優(yōu)化類(lèi)加載;3.Unabletocreatenewnativethread因係統(tǒng)線程資源耗盡,需檢查線程數(shù)限制、使用線程池、調(diào)整棧大??;4.GCoverheadlimitexceeded指GC頻繁但回收少,應(yīng)分析GC日誌,優(yōu)化

如何使用Java的日曆? 如何使用Java的日曆? Aug 02, 2025 am 02:38 AM

使用java.time包中的類(lèi)替代舊的Date和Calendar類(lèi);2.通過(guò)LocalDate、LocalDateTime和LocalTime獲取當(dāng)前日期時(shí)間;3.使用of()方法創(chuàng)建特定日期時(shí)間;4.利用plus/minus方法不可變地增減時(shí)間;5.使用ZonedDateTime和ZoneId處理時(shí)區(qū);6.通過(guò)DateTimeFormatter格式化和解析日期字符串;7.必要時(shí)通過(guò)Instant與舊日期類(lèi)型兼容;現(xiàn)代Java中日期處理應(yīng)優(yōu)先使用java.timeAPI,它提供了清晰、不可變且線

Java開(kāi)發(fā)人員的高級(jí)春季數(shù)據(jù)JPA Java開(kāi)發(fā)人員的高級(jí)春季數(shù)據(jù)JPA Jul 31, 2025 am 07:54 AM

掌握AdvancedSpringDataJPA的核心在於根據(jù)場(chǎng)景選擇合適的數(shù)據(jù)訪問(wèn)方式,並確保性能與可維護(hù)性。 1.自定義查詢中,@Query支持JPQL和原生SQL,適用於復(fù)雜關(guān)聯(lián)與聚合操作,返回結(jié)果建議通過(guò)DTO或接口投影(Projection)進(jìn)行類(lèi)型安全映射,避免使用Object[]帶來(lái)的維護(hù)難題。 2.分頁(yè)操作需結(jié)合Pageable實(shí)現(xiàn),但要警惕N 1查詢問(wèn)題,可通過(guò)JOINFETCH預(yù)加載關(guān)聯(lián)數(shù)據(jù)或使用投影減少實(shí)體加載,從而提升性能。 3.對(duì)於多條件動(dòng)態(tài)查詢,應(yīng)使用JpaSpecifica

See all articles