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

目錄
Singleton Pattern (Use with Caution)
2. Behavioral Patterns: Functional Programming to the Rescue
Strategy Pattern (Now Just a Functional Interface)
Observer Pattern (Use Reactive Streams or Listeners)
3. Structural Patterns: Still Relevant, But Leaner
Decorator Pattern (Enhanced with Lambdas)
Adapter Pattern (Use for Integration)
4. When Not to Use Design Patterns
Final Thoughts
首頁 Java java教程 現(xiàn)代爪哇的設(shè)計模式:一種實用的方法

現(xiàn)代爪哇的設(shè)計模式:一種實用的方法

Aug 02, 2025 am 05:01 AM
java 設(shè)計模式

設(shè)計模式在現(xiàn)代Java中依然相關(guān)但已演進,2. 創(chuàng)建型模式因Java 8 特性更簡潔,如Builder更乾淨(jìng)、Singleton推薦用DI替代,3. 行為型模式受益於函數(shù)式編程,Strategy可用函數(shù)接口實現(xiàn)、Observer推薦反應(yīng)式流或Consumer回調(diào),4. 結(jié)構(gòu)型模式仍適用但更輕量,Decorator可結(jié)合lambda、Adapter用於集成舊系統(tǒng),5. 避免過度設(shè)計,優(yōu)先使用Supplier、records等現(xiàn)代特性簡化實現(xiàn),最終目標(biāo)是以更少代碼實現(xiàn)清晰可維護的解決方案。

Design Patterns in Modern Java: A Practical Approach

Design patterns in modern Java aren't just relics from the early 2000s—they're still relevant, but how we use them has evolved. With features like lambdas, streams, and functional interfaces introduced in Java 8 and beyond, many classic patterns have simpler, cleaner implementations or are even obsolete. Here's a practical look at how design patterns fit into modern Java development.

Design Patterns in Modern Java: A Practical Approach

1. Creational Patterns: Simpler Than Ever

Creational patterns help manage object creation logic. In modern Java, some of these are streamlined thanks to language enhancements.

Builder Pattern (Still Useful, Now Cleaner)

The Builder pattern is widely used for constructing complex objects, especially immutable ones. With modern Java, you can make it more concise.

Design Patterns in Modern Java: A Practical Approach
 public class User {
    private final String name;
    private final int age;
    private final String email;

    private User(Builder builder) {
        this.name = builder.name;
        this.age = builder.age;
        this.email = builder.email;
    }

    public static class Builder {
        private String name;
        private int age;
        private String email;

        public Builder name(String name) {
            this.name = name;
            return this;
        }

        public Builder age(int age) {
            this.age = age;
            return this;
        }

        public Builder email(String email) {
            this.email = email;
            return this;
        }

        public User build() {
            return new User(this);
        }
    }
}

Usage:

 User user = new User.Builder()
    .name("Alice")
    .age(30)
    .email("alice@example.com")
    .build();

Tip : Use records (Java 14 ) for simple data carriers—no need for builders unless you need validation or optional fields.

Design Patterns in Modern Java: A Practical Approach

Singleton Pattern (Use with Caution)

While still seen in legacy code, the Singleton pattern is often discouraged due to testability and concurrency issues.

A thread-safe, lazy-loaded version:

 public class DatabaseConnection {
    private static volatile DatabaseConnection instance;

    private DatabaseConnection() {}

    public static DatabaseConnection getInstance() {
        if (instance == null) {
            synchronized (DatabaseConnection.class) {
                if (instance == null) {
                    instance = new DatabaseConnection();
                }
            }
        }
        return instance;
    }
}

Modern alternative : Use dependency injection (Spring, Dagger) instead. Let the container manage single instances.


2. Behavioral Patterns: Functional Programming to the Rescue

Modern Java's functional features reduce boilerplate in behavioral patterns.

Strategy Pattern (Now Just a Functional Interface)

Instead of defining multiple classes for strategies, use Function , Predicate , or custom functional interfaces.

 @FunctionalInterface
interface DiscountStrategy {
    double applyDiscount(double amount);
}

// Usage
DiscountStrategy regular = amount -> amount * 0.9;
DiscountStrategy premium = amount -> amount * 0.7;

double finalPrice = premium.applyDiscount(100);

This eliminates the need for interface implementations and makes the code more flexible and testable.


Observer Pattern (Use Reactive Streams or Listeners)

Instead of rolling your own observer setup, leverage modern libraries:

  • Java's PropertyChangeListener (for GUIs)
  • Project Reactor or RxJava for event-driven flows
  • Or simple callbacks with Consumer<T>
 List<Consumer<String>> listeners = new ArrayList<>();

public void onEvent(String event) {
    listeners.forEach(consumer -> consumer.accept(event));
}

// Subscribe
listeners.add(System.out::println);

For complex async flows, go reactive. For simple cases, lambdas work fine.


3. Structural Patterns: Still Relevant, But Leaner

These help structure classes and objects for better flexibility.

Decorator Pattern (Enhanced with Lambdas)

Commonly used in I/O streams (eg, BufferedInputStream wraps FileInputStream ).

You can apply it functionally:

 @FunctionalInterface
interface DataService {
    String fetchData();

    default DataService withLogging(DataService ds) {
        return () -> {
            System.out.println("Fetching data...");
            return ds.fetchData();
        };
    }
}

But prefer composition over complex hierarchies. Modern design favors small, composable components.


Adapter Pattern (Use for Integration)

When integrating with legacy or third-party APIs, the adapter pattern shines.

 class WeatherService {
    public String getWeather() {
        return "Sunny";
    }
}

interface ForecastService {
    String getCurrentForecast();
}

class WeatherAdapter implements ForecastService {
    private WeatherService service;

    public WeatherAdapter(WeatherService service) {
        this.service = service;
    }

    @Override
    public String getCurrentForecast() {
        return "Forecast: " service.getWeather();
    }
}

Use case : Wrapping old APIs to fit modern interfaces—still very practical.


4. When Not to Use Design Patterns

  • Overengineering : Don't force a pattern where a simple method or lambda suffices.
  • Premature abstraction : Wait until duplication or complexity emerges.
  • Using patterns just because : If your team doesn't need it, skip it.

Example : Instead of a full Factory Method pattern, consider a Supplier<T> :

 Map<String, Supplier<Report>> factories = Map.of(
    "PDF", PdfReport::new,
    "CSV", CsvReport::new
);

Report report = factories.get("PDF").get();

Clean, readable, and functional.


Final Thoughts

Design patterns aren't obsolete—they've just matured. Modern Java gives us tools to implement them more elegantly:

  • Use lambdas and functional interfaces to simplify behavioral patterns.
  • Prefer composition and DI over rigid inheritance.
  • Leverage records and var for cleaner data structures.
  • Reach for reactive programming instead of manual observer setups.

The goal isn't to memorize patterns—it's to solve problems clearly and maintainably. With modern Java, you can do that with less code and better readability.

Basically: know the patterns, but don't be a slave to them.

以上是現(xiàn)代爪哇的設(shè)計模式:一種實用的方法的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

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

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

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

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

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

熱門話題

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

settings.json文件位於用戶級或工作區(qū)級路徑,用於自定義VSCode設(shè)置。 1.用戶級路徑: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ū)級路徑:項目根目錄下的.vscode/settings

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

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

在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 Itertools組合示例 Python Itertools組合示例 Jul 31, 2025 am 09:53 AM

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

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

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

故障排除常見的java`ofmemoryError`場景'' 故障排除常見的java`ofmemoryError`場景'' Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError:Javaheapspace表示堆內(nèi)存不足,需檢查大對象處理、內(nèi)存洩漏及堆設(shè)置,通過堆轉(zhuǎn)儲分析工具定位並優(yōu)化代碼;2.Metaspace錯誤因類元數(shù)據(jù)過多,常見於動態(tài)類生成或熱部署,應(yīng)限制MaxMetaspaceSize並優(yōu)化類加載;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包中的類替代舊的Date和Calendar類;2.通過LocalDate、LocalDateTime和LocalTime獲取當(dāng)前日期時間;3.使用of()方法創(chuàng)建特定日期時間;4.利用plus/minus方法不可變地增減時間;5.使用ZonedDateTime和ZoneId處理時區(qū);6.通過DateTimeFormatter格式化和解析日期字符串;7.必要時通過Instant與舊日期類型兼容;現(xiàn)代Java中日期處理應(yīng)優(yōu)先使用java.timeAPI,它提供了清晰、不可變且線

了解Java虛擬機(JVM)內(nèi)部 了解Java虛擬機(JVM)內(nèi)部 Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

See all articles