汪立丞
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
--- title: 單例模式及kotlin object運作原理 tags: Android 概念整理 --- ## 簡介 * 單例模式是一種軟體設計模式,規則是每個類別只能有一個實例存在,並且能提供全域訪問。當多個類別呼叫它時,拿到的都會是同一個實例。該singleton類別可以自己產生一個自己的實例,也可以透過工廠類別來產生。 * 在一個典型的APP中,我們常只需要物件的一個全域實例,無論是直接使用它還是簡單地將它傳遞給另一個類。包括OkHttpClient, HttpLoggingInterceptor, retrofit,Gson,SharedPreferences和倉庫類等。 如果我們把這些類產生實體了多個物件,我們就會遇到許多問題,比如異常的APP反應,資源過度使用和其他混亂的結果。 ## 在java中實現單例模式 ```java= public class Singleton{ private static Singleton instance = null; private Singleton(){ //構造函數 } private synchronized static void createInstance(){ if(instance == null){ instance = new Singleton(); } } public static Singleton getInstance(){ if(instance == null) createInstance(); return instance; } } ``` * 裡面使用到synchronized關鍵字,原因是要保護執行緒安全,表示這個function裡面一次只有一個執行緒能夠進入,其他執行緒要在外面乖乖排隊。這樣就不會有多個執行緒因為同時執行到此function而產生多個實例的問題。 * 缺點是會有執行緒堵塞的問題,降低整體性能。 ## 在kotlin中實現單例模式 ```kotlin= class MainActivity : AppCompatActivity() { object test{ } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } } ``` 一行程式碼,結束。 * 此用法稱為「Object Declaration」。 * `object`關鍵字代表其包含了上面單例的特性。我們試著把它decompile就會變成下面這樣。 ```java= public static final class test { public static final MainActivity.test INSTANCE; private test() { } static { MainActivity.test var0 = new MainActivity.test(); INSTANCE = var0; } } ``` * 會發現跟上面的java寫法非常相似。 * 會發現它在static作用域裡幫你實例化了test類別。而jvm虛擬機在載入類別時,就會執行static作用域,也就是說**kotlin中的object{}都會在一開始就被實例化** 對於static與靜態用法可以參考[java的靜態成員與特性](https://hackmd.io/gnoEw-smRm2ZbcGH-0Zjww) * 要注意的是,object沒有用synchronized來保障執行緒安全,這部分必須自己處理。 那如果我們想在static區塊加入更多東西,好讓他們在app一開啟就被執行呢? 寫在`init{}`初始化區塊裡就可以啦~ ```kotlin= object test{ init{ println("init") } fun wangwang(){ println("wangwang") } } ``` decompile之後 ```java= public static final class test { public static final MainActivity.test INSTANCE; public final void wangwang() { String var1 = "wangwang"; System.out.println(var1); } //構造函數一定是空的 private test() { } static { MainActivity.test var0 = new MainActivity.test(); INSTANCE = var0; String var1 = "init"; System.out.println(var1); } } } ``` * 發現static區塊確實多了我們新增的兩行程式碼。 那可能有人擔心另一個問題,類加載的時候就初始化構造單例,是不是對資源的利用不太好? 這一點問題不大,虛擬機在運行程序的時候,並不是在啟動時就將所有的類,都加載進來並初始化完成,而是一種按需加載的策略,在真正使用它的時候,才會初始化。 例如:new Class、調用靜態方法、反射、調用 Class.forName() 方法等。這一點可以通過本文介紹的單例實現,在 init 塊中輸出 Log,看看 Log 何時輸出來驗證。 ## 參考資料: [1. 講解kotlin單例、帶參單例及封裝](https://kknews.cc/zh-tw/code/jkg6k4y.html)

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully