最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android/Java中創(chuàng)建類實例的各種模式實例代碼

 更新時間:2025年09月08日 10:00:24   作者:滬cares  
這篇文章主要介紹了Android/Java中創(chuàng)建類實例各種模式的相關(guān)資料,包括New關(guān)鍵字、靜態(tài)工廠方法、建造者模式、單例模式、依賴注入、抽象工廠模式、原型模式和Reflection,每個模式有其特點(diǎn)和適用場景,需要的朋友可以參考下

創(chuàng)建型模式總覽

模式名稱核心思想使用頻率難度
new 關(guān)鍵字直接調(diào)用構(gòu)造函數(shù)??????
靜態(tài)工廠方法通過靜態(tài)方法創(chuàng)建實例??????
建造者模式分步構(gòu)建復(fù)雜對象??????
單例模式確保全局唯一實例??????
依賴注入外部容器管理依賴????????
抽象工廠模式創(chuàng)建相關(guān)對象家族??????
原型模式通過克隆創(chuàng)建實例????
反射創(chuàng)建運(yùn)行時動態(tài)創(chuàng)建?????

1. new 關(guān)鍵字 (Direct Instantiation)

名詞解釋

最基礎(chǔ)的實例創(chuàng)建方式,直接調(diào)用類的構(gòu)造函數(shù)來創(chuàng)建對象實例。

核心特點(diǎn)

// 基本語法
ClassName object = new ClassName(arguments);

// 示例
User user = new User("Alice", 25);
TextView textView = new TextView(context);

優(yōu)點(diǎn)

  • 簡單直觀:語法簡單,學(xué)習(xí)成本低
  • 性能最佳:沒有額外的開銷,直接調(diào)用構(gòu)造函數(shù)
  • 編譯時檢查:類型安全,編譯時就能發(fā)現(xiàn)錯誤
  • 明確性:代碼意圖清晰,易于理解

缺點(diǎn)

  • 緊耦合:客戶端代碼直接依賴具體實現(xiàn)類
  • 缺乏靈活性:無法在創(chuàng)建過程中加入額外邏輯
  • 難以測試:難以替換為Mock對象進(jìn)行單元測試
  • 構(gòu)造函數(shù)膨脹:參數(shù)過多時代碼難以維護(hù)

適用場景

  • 簡單的數(shù)據(jù)對象(POJO、DTO)
  • 在類內(nèi)部創(chuàng)建輔助工具對象
  • 性能要求極高的場景
  • 原型開發(fā)或一次性代碼

Android 示例

// 創(chuàng)建基礎(chǔ)UI組件
TextView textView = new TextView(context);
Button button = new Button(context);

// 創(chuàng)建數(shù)據(jù)對象
Intent intent = new Intent(context, MainActivity.class);
Bundle bundle = new Bundle();

2. 靜態(tài)工廠方法 (Static Factory Method)

名詞解釋

通過類的靜態(tài)方法來創(chuàng)建實例,而不是直接調(diào)用構(gòu)造函數(shù)。

核心特點(diǎn)

public class Connection {
    private String url;
    
    private Connection(String url) {
        this.url = url;
    }
    
    // 靜態(tài)工廠方法
    public static Connection create(String url) {
        validateUrl(url); // 添加驗證邏輯
        return new Connection(url);
    }
    
    // 有名稱的工廠方法
    public static Connection createSecureConnection() {
        return new Connection("https://secure.example.com");
    }
}

// 使用
Connection conn = Connection.create("https://api.example.com");

優(yōu)點(diǎn)

  • 有意義的名稱:方法名可以描述創(chuàng)建邏輯
  • 控制實例化:可以緩存實例、參數(shù)驗證、返回子類
  • 降低耦合:客戶端只需知道工廠方法接口
  • 靈活性:可以返回接口而非具體實現(xiàn)

缺點(diǎn)

  • 無法繼承:如果類沒有公共構(gòu)造器,則無法被繼承
  • 不易發(fā)現(xiàn):工廠方法與其他靜態(tài)方法混在一起
  • 需要文檔:需要說明哪些是工廠方法

適用場景

  • 需要控制創(chuàng)建邏輯(驗證、緩存)
  • 創(chuàng)建過程有名稱區(qū)分不同行為
  • 返回接口而非具體實現(xiàn)
  • 需要緩存或重用實例

Android 示例

// Intent 工廠方法
Intent chooserIntent = Intent.createChooser(shareIntent, "Share via");

// Bitmap 工廠方法
Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);

// Uri 解析
Uri uri = Uri.parse("content://com.example.provider/data");

3. 建造者模式 (Builder Pattern)

名詞解釋

通過一個建造者類來分步構(gòu)建復(fù)雜對象,特別適合參數(shù)多的場景。

核心特點(diǎn)

public class AlertDialogConfig {
    private final String title;
    private final String message;
    private final boolean cancelable;
    
    private AlertDialogConfig(Builder builder) {
        this.title = builder.title;
        this.message = builder.message;
        this.cancelable = builder.cancelable;
    }
    
    public static class Builder {
        private String title;
        private String message;
        private boolean cancelable = true;
        
        public Builder setTitle(String title) {
            this.title = title;
            return this;
        }
        
        public Builder setMessage(String message) {
            this.message = message;
            return this;
        }
        
        public Builder setCancelable(boolean cancelable) {
            this.cancelable = cancelable;
            return this;
        }
        
        public AlertDialogConfig build() {
            return new AlertDialogConfig(this);
        }
    }
}

// 使用
AlertDialogConfig config = new AlertDialogConfig.Builder()
    .setTitle("Warning")
    .setMessage("Are you sure?")
    .setCancelable(false)
    .build();

優(yōu)點(diǎn)

  • 極佳的可讀性:鏈?zhǔn)秸{(diào)用清晰表達(dá)意圖
  • 參數(shù)靈活性:處理多個可選參數(shù)
  • 不可變對象:適合創(chuàng)建不可變對象
  • 參數(shù)驗證:在build()方法中集中驗證
  • 分步構(gòu)建:可以分多個步驟構(gòu)建

缺點(diǎn)

  • 代碼冗余:需要編寫大量的樣板代碼
  • 創(chuàng)建開銷:需要先創(chuàng)建Builder對象
  • 學(xué)習(xí)成本:對新手可能不太直觀

適用場景

  • 具有多個可選參數(shù)的對象(4個或更多)
  • 需要創(chuàng)建不可變對象
  • 參數(shù)配置復(fù)雜且需要良好可讀性
  • 需要分步驟構(gòu)建的復(fù)雜對象

Android 示例

// Notification 建造者
Notification notification = new NotificationCompat.Builder(context, "channel_id")
    .setContentTitle("Title")
    .setContentText("Message")
    .setSmallIcon(R.drawable.ic_notification)
    .build();

// Retrofit 建造者
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

4. 單例模式 (Singleton Pattern)

名詞解釋

確保一個類只有一個實例,并提供全局訪問點(diǎn)。

核心特點(diǎn)

// 雙重檢查鎖實現(xiàn)
public class AppManager {
    private static volatile AppManager instance;
    private final Context appContext;
    
    private AppManager(Context context) {
        this.appContext = context.getApplicationContext();
    }
    
    public static AppManager getInstance(Context context) {
        if (instance == null) {
            synchronized (AppManager.class) {
                if (instance == null) {
                    instance = new AppManager(context);
                }
            }
        }
        return instance;
    }
}

// 靜態(tài)內(nèi)部類實現(xiàn)(推薦)
public class DatabaseHelper {
    private DatabaseHelper() {}
    
    private static class Holder {
        static final DatabaseHelper INSTANCE = new DatabaseHelper();
    }
    
    public static DatabaseHelper getInstance() {
        return Holder.INSTANCE;
    }
}

優(yōu)點(diǎn)

  • 全局唯一訪問點(diǎn):確保整個應(yīng)用中使用同一個實例
  • 節(jié)省資源:避免重復(fù)創(chuàng)建昂貴對象
  • 延遲初始化:支持按需創(chuàng)建
  • 全局狀態(tài)管理:方便管理應(yīng)用級狀態(tài)

缺點(diǎn)

  • 全局狀態(tài):可能導(dǎo)致隱藏的耦合
  • 線程安全問題:需要小心處理多線程環(huán)境
  • 測試?yán)щy:全局狀態(tài)使得單元測試復(fù)雜
  • 內(nèi)存泄漏風(fēng)險:可能持有Context導(dǎo)致內(nèi)存泄漏

適用場景

  • 全局配置管理
  • 資源密集型對象(數(shù)據(jù)庫連接、網(wǎng)絡(luò)客戶端)
  • 需要嚴(yán)格單例的系統(tǒng)服務(wù)
  • 應(yīng)用級別的狀態(tài)管理

Android 示例

// Application 類本身就是單例
public class MyApp extends Application {
    private static MyApp instance;
    
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }
    
    public static MyApp getInstance() {
        return instance;
    }
}

// 使用單例
ImageLoader.getInstance().loadImage(url, imageView);

5. 依賴注入 (Dependency Injection)

名詞解釋

對象的依賴由外部容器提供,而不是自己創(chuàng)建,實現(xiàn)控制反轉(zhuǎn)。

核心特點(diǎn)

// 手動依賴注入
public class UserRepository {
    private final ApiService apiService;
    
    public UserRepository(ApiService apiService) {
        this.apiService = apiService; // 依賴注入
    }
}

// 使用 Dagger/Hilt
@Module
@InstallIn(SingletonComponent.class)
public class NetworkModule {
    @Provides
    @Singleton
    public Retrofit provideRetrofit() {
        return new Retrofit.Builder()
            .baseUrl("https://api.example.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    }
}

@AndroidEntryPoint
public class MainActivity extends AppCompatActivity {
    @Inject
    Retrofit retrofit; // 自動注入
}

優(yōu)點(diǎn)

  • 極致解耦:組件間不直接依賴
  • 易于測試:可以輕松注入Mock對象
  • 生命周期管理:框架管理對象的創(chuàng)建和銷毀
  • 代碼復(fù)用:依賴項可在多處共享
  • 配置集中化:依賴配置集中在模塊中

缺點(diǎn)

  • 學(xué)習(xí)曲線陡峭:需要理解復(fù)雜的概念
  • 編譯時開銷:注解處理增加編譯時間
  • 調(diào)試?yán)щy:錯誤信息可能不直觀
  • 過度工程:小項目可能過于復(fù)雜

適用場景

  • 中大型項目,需要良好的架構(gòu)
  • 需要高度可測試性的項目
  • 復(fù)雜的依賴關(guān)系圖
  • 團(tuán)隊協(xié)作開發(fā),需要統(tǒng)一架構(gòu)

Android 示例

// Hilt 注入 ViewModel
@HiltViewModel
public class MainViewModel extends ViewModel {
    private final UserRepository repository;
    
    @Inject
    public MainViewModel(UserRepository repository) {
        this.repository = repository;
    }
}

// Activity 中使用
@AndroidEntryPoint
public class MainActivity extends AppCompatActivity {
    @Inject
    MainViewModel viewModel;
}

6. 抽象工廠模式 (Abstract Factory Pattern)

名詞解釋

創(chuàng)建相關(guān)或依賴對象的家族,而不需要指定具體類。

核心特點(diǎn)

public interface ThemeFactory {
    Button createButton();
    TextView createTextView();
    Dialog createDialog();
}

public class LightThemeFactory implements ThemeFactory {
    @Override
    public Button createButton() {
        Button button = new Button(context);
        button.setBackgroundColor(Color.WHITE);
        return button;
    }
    // 其他方法...
}

public class DarkThemeFactory implements ThemeFactory {
    @Override
    public Button createButton() {
        Button button = new Button(context);
        button.setBackgroundColor(Color.BLACK);
        return button;
    }
    // 其他方法...
}

優(yōu)點(diǎn)

  • 產(chǎn)品族一致性:確保創(chuàng)建的對象相互兼容
  • 開閉原則:易于添加新的產(chǎn)品族
  • 客戶端解耦:客戶端與具體實現(xiàn)解耦
  • 統(tǒng)一接口:提供統(tǒng)一的創(chuàng)建接口

缺點(diǎn)

  • 復(fù)雜度高:需要定義大量接口和類
  • 難以擴(kuò)展:添加新產(chǎn)品需要修改工廠接口
  • 過度設(shè)計:簡單場景下顯得過于復(fù)雜

適用場景

  • 需要創(chuàng)建相關(guān)或依賴的對象家族
  • 系統(tǒng)需要獨(dú)立于產(chǎn)品的創(chuàng)建、組合和表示
  • 需要提供多個產(chǎn)品族,但只使用其中一族
  • GUI 主題系統(tǒng)、跨平臺UI組件

7. 原型模式 (Prototype Pattern)

名詞解釋

通過克隆現(xiàn)有對象來創(chuàng)建新實例,避免昂貴的初始化過程。

核心特點(diǎn)

public class UserProfile implements Cloneable {
    private String username;
    private Map<String, Object> preferences;
    
    public UserProfile(String username) {
        this.username = username;
        this.preferences = loadPreferences(); // 耗時操作
    }
    
    @Override
    public UserProfile clone() {
        try {
            UserProfile cloned = (UserProfile) super.clone();
            cloned.preferences = new HashMap<>(this.preferences); // 深拷貝
            return cloned;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }
}

// 使用
UserProfile original = new UserProfile("user123");
UserProfile copy = original.clone(); // 比 new 快很多

優(yōu)點(diǎn)

  • 性能優(yōu)化:避免昂貴的初始化過程
  • 簡化創(chuàng)建:簡化復(fù)雜對象的創(chuàng)建過程
  • 動態(tài)配置:可以在運(yùn)行時克隆配置好的對象

缺點(diǎn)

  • 深拷貝復(fù)雜:需要小心處理所有引用類型
  • 克隆方法濫用:可能被用于規(guī)避構(gòu)造器邏輯
  • 內(nèi)存占用:可能占用更多內(nèi)存

適用場景

  • 創(chuàng)建對象成本很高(需要大量計算或IO)
  • 需要創(chuàng)建相似但略有不同的對象
  • 系統(tǒng)需要獨(dú)立于如何創(chuàng)建、組合產(chǎn)品
  • 游戲開發(fā)中的對象池

8. 反射創(chuàng)建 (Reflection)

名詞解釋

在運(yùn)行時動態(tài)創(chuàng)建對象實例,通過類名等信息來實例化對象。

核心特點(diǎn)

public class ObjectFactory {
    public static <T> T createInstance(String className) {
        try {
            Class<?> clazz = Class.forName(className);
            return (T) clazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("創(chuàng)建實例失敗", e);
        }
    }
}

// 使用
String className = "com.example.MyClass";
MyClass obj = ObjectFactory.createInstance(className);

優(yōu)點(diǎn)

  • 極度靈活:可以在運(yùn)行時動態(tài)創(chuàng)建任何類的實例
  • 實現(xiàn)插件系統(tǒng):可以加載并實例化未知的類
  • 解耦:客戶端不需要知道具體類名

缺點(diǎn)

  • 性能差:比直接調(diào)用構(gòu)造器慢很多
  • 安全性問題:可以繞過訪問控制
  • 編譯時檢查缺失:錯誤只能在運(yùn)行時發(fā)現(xiàn)
  • 代碼可讀性差:難以理解和維護(hù)

適用場景

  • 框架開發(fā)(如依賴注入容器)
  • 動態(tài)加載類(插件系統(tǒng))
  • 序列化/反序列化庫
  • 配置驅(qū)動的對象創(chuàng)建

總結(jié)對比表

模式優(yōu)點(diǎn)缺點(diǎn)適用場景使用頻率
new 關(guān)鍵字簡單、高性能、明確緊耦合、缺乏靈活性簡單對象、內(nèi)部使用?????
靜態(tài)工廠有名稱、可控制、可緩存不能繼承、不易發(fā)現(xiàn)需要控制創(chuàng)建邏輯????
建造者參數(shù)靈活、可讀性好代碼冗余、創(chuàng)建開銷多參數(shù)對象、配置復(fù)雜???
單例全局唯一、節(jié)省資源全局狀態(tài)、測試?yán)щy全局管理、資源密集型????
依賴注入解耦、易測試、生命周期管理學(xué)習(xí)曲線陡、調(diào)試復(fù)雜中大型項目、需要架構(gòu)????
抽象工廠產(chǎn)品族一致性、開閉原則復(fù)雜度高、難以擴(kuò)展創(chuàng)建相關(guān)對象家族??
原型性能優(yōu)化、避免昂貴初始化深拷貝復(fù)雜、可能濫用創(chuàng)建成本高的相似對象?
反射極度靈活、動態(tài)創(chuàng)建性能差、安全問題框架開發(fā)、插件系統(tǒng)?

Android 開發(fā)建議

  1. 簡單場景:優(yōu)先使用 new 和靜態(tài)工廠方法
  2. UI 組件:使用建造者模式(AlertDialog、Notification)
  3. 業(yè)務(wù)邏輯:使用依賴注入(Dagger/Hilt)
  4. 全局服務(wù):謹(jǐn)慎使用單例模式,注意內(nèi)存泄漏
  5. 性能敏感:考慮原型模式避免重復(fù)昂貴操作
  6. 框架開發(fā):在必要時使用反射和抽象工廠

到此這篇關(guān)于Android/Java中創(chuàng)建類實例的各種模式的文章就介紹到這了,更多相關(guān)Java創(chuàng)建類實例模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Spring Boot使用模板freemarker的示例代碼

    Spring Boot使用模板freemarker的示例代碼

    本篇文章主要介紹了Spring Boot使用模板freemarker的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-10-10
  • Maven本地倉庫的配置以及修改默認(rèn).m2倉庫位置

    Maven本地倉庫的配置以及修改默認(rèn).m2倉庫位置

    今天小編就為大家分享一篇關(guān)于Maven本地倉庫的配置以及修改默認(rèn).m2倉庫位置的文章,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2018-10-10
  • Java多態(tài)到底都有啥好處

    Java多態(tài)到底都有啥好處

    Java中的多態(tài)性有兩種類型:編譯時多態(tài)(靜態(tài)綁定)和運(yùn)行時多態(tài)(動態(tài)綁定)。方法重載是靜態(tài)多態(tài)的一個例子,而方法重寫是動態(tài)多態(tài)的一個例子,接下來通過本文給大家分享Java多態(tài)到底教了我干啥?有啥好處,一起了解下吧
    2021-05-05
  • SpringBoot實現(xiàn)密碼安全存儲的五種方式小結(jié)

    SpringBoot實現(xiàn)密碼安全存儲的五種方式小結(jié)

    項目開發(fā)中,密碼安全存儲是非常關(guān)鍵的一環(huán),作為開發(fā)者,我們需要確保用戶的密碼在存儲時被安全地加密,避免因數(shù)據(jù)泄露而造成嚴(yán)重后果,所以本文給大家介紹了SpringBoot實現(xiàn)密碼安全存儲的5種方式,需要的朋友可以參考下
    2025-03-03
  • SpringBoot Swagger2 接口規(guī)范示例詳解

    SpringBoot Swagger2 接口規(guī)范示例詳解

    Swagger(在谷歌、IBM、微軟等公司的支持下)做了一個公共的文檔風(fēng)格來填補(bǔ)上述問題,在本文中,我們將會學(xué)習(xí)怎么使用Swagger的 Swagger2注解去生成REST API文檔,感興趣的朋友一起看看吧
    2023-12-12
  • RestTemplate如何添加請求頭headers和請求體body

    RestTemplate如何添加請求頭headers和請求體body

    這篇文章主要介紹了RestTemplate如何添加請求頭headers和請求體body問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • Spring和Mybatis整合的原理詳解

    Spring和Mybatis整合的原理詳解

    這篇文章主要介紹了Spring和Mybatis整合的原理詳解,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-07-07
  • Java實現(xiàn)將數(shù)字日期翻譯成英文單詞的工具類實例

    Java實現(xiàn)將數(shù)字日期翻譯成英文單詞的工具類實例

    這篇文章主要介紹了Java實現(xiàn)將數(shù)字日期翻譯成英文單詞的工具類,結(jié)合完整實例形式分析了Java日期轉(zhuǎn)換與字符串操作相關(guān)實現(xiàn)技巧,需要的朋友可以參考下
    2017-09-09
  • 基于Java代碼實現(xiàn)數(shù)字在數(shù)組中出現(xiàn)次數(shù)超過一半

    基于Java代碼實現(xiàn)數(shù)字在數(shù)組中出現(xiàn)次數(shù)超過一半

    這篇文章主要介紹了基于Java代碼實現(xiàn)數(shù)字在數(shù)組中出現(xiàn)次數(shù)超過一半的相關(guān)資料,需要的朋友可以參考下
    2016-02-02
  • 淺談JAVA 內(nèi)存流的實現(xiàn)

    淺談JAVA 內(nèi)存流的實現(xiàn)

    這篇文章主要介紹了淺談JAVA 內(nèi)存流的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-02-02

最新評論

财经| 齐河县| 和顺县| 辰溪县| 申扎县| 海盐县| 宣恩县| 南乐县| 临武县| 虞城县| 西畴县| 新和县| 扎囊县| 墨江| 台东县| 麟游县| 宁南县| 宜城市| 香港| 南江县| 中方县| 吉林市| 北辰区| 武隆县| 历史| 习水县| 休宁县| 柞水县| 安庆市| 米林县| 阿鲁科尔沁旗| 兴山县| 桓仁| 常熟市| 思茅市| 新疆| 大厂| 崇明县| 平江县| 息烽县| 崇州市|