![Fragmented - An Android Developer Podcast artwork](https://is2-ssl.mzstatic.com/image/thumb/Podcasts123/v4/00/f5/c0/00f5c0f5-91e8-c52a-3a5c-8187c4b43797/mza_4290848285973845015.jpg/100x100bb.jpg)
018: Effective Java for Android developers : Item 3
Fragmented - An Android Developer Podcast
English - October 08, 2015 17:49 - 11 minutes - 5.48 MB - ★★★★★ - 53 ratingsTechnology Education How To android developer java androiddev kotlin Homepage Download Apple Podcasts Google Podcasts Overcast Castro Pocket Casts RSS feed
In this mini Fragment, we introduce Joshua's third Item: Enforce the Singleton property with a private constructor or an enum type.
Stay tuned for more items from our "Effective Java for Android developers" Fragment series.
Show Notes
Effective Java (2nd Edition) - Joshua Bloch
Enforce the Singleton property with a private constructor or an enum type
Approaches
Create a public static final INSTANCE variable and privatize constructor
Same as 1 but privatize variable and expose access with provide factory method getInstance
Single element Enums
Considerations
First two approaches are open to Serialization attacks (deserializing creates new instance)
To protect from those declare the fields transient + provide readResolve method
Enums are concise, provide free serialization and ironclad Singleton guarantees and are functionally equivalent to first approach
Supplemental reading (for the diligent ones that follow shownotes)
Dianne Hackborn regretting exposing the base Application class
DH again saying Application is a Singleton with crappier semantics
Elvis sightings
Contact us:
@fragmentedcast [twitter.com]
@donnfelker [twitter.com]
@kaushikgopal [twitter.com]