SlideShare ist ein Scribd-Unternehmen logo
1 von 20
codecentric AG
Dusan Zamurovic
A pattern discussion
codecentric AG
 Singleton pattern
 things we sometimes forget
 Dependency injection / Inversion of Control
 Paired with Singleton
 Example without third party library
TOPICS
codecentric AG
 What Singleton pattern does?
 Implementation examples
 Wrong implementations
 Implementations that look okay
 Right implementations
Singleton
codecentric AG
Singleton 01
public class Singleton01 {
// TODO Make this class final?
private static Singleton01 instance = null;
private Singleton01() {
// Private constructor prevents instantiation,
// but also prevents sub-classing.
}
public static Singleton01 getInstance() {
if (instance == null) {
instance = new Singleton01();
}
return instance;
}
}
codecentric AG
Singleton 02
private static Singleton02 instance = null;
public static Singleton02 getInstance() {
if (instance == null) {
simulateMultiThreadEnvironment();
instance = new Singleton02();
}
return instance;
}
// Not synchronized, not thread safe.
codecentric AG
Singleton 03
private static Singleton03 instance = null;
public synchronized static Singleton03 getInstance() {
if (instance == null) {
simulateMultiThreadEnvironment();
instance = new Singleton03();
}
return instance;
}
// Synchronized, thread safe.
codecentric AG
Singleton 04
private static Singleton04 instance = null;
public static Singleton04 getInstance() {
if (instance == null) {
synchronized (Singleton04.class) {
simulateMultiThreadEnvironment();
instance = new Singleton04();
}
}
return instance;
}
// Synchronized, performance optimization, not thread safe.
codecentric AG
Singleton 05
private static Singleton05 instance = null;
public static Singleton05 getInstance() {
if (instance == null) {
synchronized (Singleton05.class) {
if (instance == null) {
instance = new Singleton05();
}
}
}
return instance;
}
// Double-checked locking – doesn’t work prior to Java 1.5.
codecentric AG
Singleton 06
private static final Singleton06 INSTANCE = new Singleton06();
public static Singleton06 getInstance() {
return INSTANCE;
}
// Eager instantiating of the class. This works.
// What about serialization/deserialization?
codecentric AG
Singleton 06 Serializable
public class Singleton06 implements Serializable {
private static final Singleton06 INSTANCE = new Singleton06();
public static Singleton06 getInstance() {
return INSTANCE;
}
}
protected Object readResolve() {
return getInstance();
}
codecentric AG
Singleton 07
public enum Singleton07 {
INSTANCE;
}
// What about serialization/deserialization?
// What about reflection?
codecentric AG
 What is DI / IoC?
 Implementation example
 No third party library
Dependency Injection / Inversion of Control
codecentric AG
Dependency Injection / Inversion of Control
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Inject {
}
// @Component is used to mark a class – a thing to inject.
// @Inject is used to mark a field – a place to inject.
codecentric AG
Dependency Injection / Inversion of Control
@Component
public class Controller {
@Inject
private ManageCapable manager;
…
}
@Component
public class Manager implements ManageCapable {
@Inject
private Repository repository;
…
}
codecentric AG
Dependency Injection / Inversion of Control
@Component
public class Repository {
public Resourcable save(Resourcable aResource) {
// Here we "persist" the given resource
// and return it like we really did it.
return aResource;
}
}
codecentric AG
Dependency Injection / Inversion of Control
public class PackageScanner {
…
}
public class ClassScanner {
…
}
public class DependencyInjectionManager {
…
}
// https://github.com/dzamurovic/meetup_singleton.git
codecentric AG
Dependency Injection / Inversion of Control
public synchronized void run() throws Exception {
if (initialized) {
return;
}
// Find classes annotated with @Component.
List<Class> components = packageScanner.findAnnotatedClasses(
"rs.codecentric.meetup.diioc.example", Component.class);
// For each component...
for (Class component : components) {
Class definingClass = classScanner.getDefiningClass(component);
// ... check if its instance already exists...
if (!graph.containsKey(definingClass)) {
// ... and instantiate it, if it doesn't.
String className = component.getName();
graph.put(definingClass, Class.forName(component.getName()).newInstance());
}
}
}
codecentric AG
Dependency Injection / Inversion of Control
// For each object that is created...
for (Iterator<Class> classIterator = graph.keySet().iterator();
classIterator.hasNext();) {
Class definingClass = classIterator.next();
Object object = graph.get(definingClass);
// ... find dependencies it needs, ...
for (Field f : classScanner.findAnnotatedFields(object.getClass(),
Inject.class)) {
if (!graph.containsKey(f.getType())) {
// ... throw an error if a dependency cannot be satisfied, ...
}
// ... or set a value of the dependency.
Object dependency = graph.get(f.getType());
f.set(object, dependency);
}
}
initialized = true;
}
codecentric AG
Dependency Injection / Inversion of Control
public static void main(String args[]) throws Exception {
final DependencyInjectionManager diManager =
DependencyInjectionManager.getInstance();
Thread t1 = new DependencyInjectionThread("DI-thread-0", diManager);
Thread t2 = …
t1.start();
t2.st…
t1.join();
t2.j…
diManager.describeDependencyGraph();
}
codecentric AG
QUESTIONS?
https://github.com/dzamurovic/meetup_singleton.git
dusan.zamurovic@codecentric.de
@ezamur
@CodingSerbia
http://www.meetup.com/Coding-Serbia/
www.codecentric.de
www.codecentric.rs
https://blog.codecentric.de
6/27/2014 20

Weitere ähnliche Inhalte

Was ist angesagt?

Java Serialization
Java SerializationJava Serialization
Java Serializationjeslie
 
Unit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftUnit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftallanh0526
 
Using ReasonML For Your Next JavaScript Project
Using ReasonML For Your Next JavaScript ProjectUsing ReasonML For Your Next JavaScript Project
Using ReasonML For Your Next JavaScript ProjectRoy Derks
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksSamundra khatri
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mockPranalee Rokde
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 
Looking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelopLooking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelopPVS-Studio
 
A fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBoxA fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBoxPVS-Studio
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 KotlinVMware Tanzu
 
Java Libraries You Can't Afford to Miss
Java Libraries You Can't Afford to MissJava Libraries You Can't Afford to Miss
Java Libraries You Can't Afford to MissAndres Almiray
 
Linq & lambda overview C#.net
Linq & lambda overview C#.netLinq & lambda overview C#.net
Linq & lambda overview C#.netDhairya Joshi
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
Padroes Projeto
Padroes ProjetoPadroes Projeto
Padroes Projetolcbj
 

Was ist angesagt? (20)

CDI: How do I ?
CDI: How do I ?CDI: How do I ?
CDI: How do I ?
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Mockito
MockitoMockito
Mockito
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Unit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftUnit testing in xcode 8 with swift
Unit testing in xcode 8 with swift
 
Using ReasonML For Your Next JavaScript Project
Using ReasonML For Your Next JavaScript ProjectUsing ReasonML For Your Next JavaScript Project
Using ReasonML For Your Next JavaScript Project
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Looking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelopLooking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelop
 
A fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBoxA fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBox
 
Power mock
Power mockPower mock
Power mock
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
 
Java Libraries You Can't Afford to Miss
Java Libraries You Can't Afford to MissJava Libraries You Can't Afford to Miss
Java Libraries You Can't Afford to Miss
 
Linq & lambda overview C#.net
Linq & lambda overview C#.netLinq & lambda overview C#.net
Linq & lambda overview C#.net
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Control statements
Control statementsControl statements
Control statements
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Padroes Projeto
Padroes ProjetoPadroes Projeto
Padroes Projeto
 

Ähnlich wie Meetup - Singleton & DI/IoC

Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Arsen Gasparyan
 
RIBs - Fragments which work
RIBs - Fragments which workRIBs - Fragments which work
RIBs - Fragments which workDmitry Zaytsev
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objectsSandeep Chawla
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConos890
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)David McCarter
 
Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Sameer Rathoud
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805LearningTech
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805LearningTech
 
Singleton Pattern
Singleton PatternSingleton Pattern
Singleton PatternHany Omar
 
It's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journeyIt's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journeyThiago “Fred” Porciúncula
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Oliver Gierke
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonJonathan Simon
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsRavi Bhadauria
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014First Tuesday Bergen
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014Matthias Noback
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentJayaprakash R
 

Ähnlich wie Meetup - Singleton & DI/IoC (20)

Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
 
RIBs - Fragments which work
RIBs - Fragments which workRIBs - Fragments which work
RIBs - Fragments which work
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheCon
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
 
Singleton Pattern
Singleton PatternSingleton Pattern
Singleton Pattern
 
It's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journeyIt's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journey
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and Singleton
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 
Dependency Injection for Android
Dependency Injection for AndroidDependency Injection for Android
Dependency Injection for Android
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 

Kürzlich hochgeladen

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 

Kürzlich hochgeladen (20)

Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 

Meetup - Singleton & DI/IoC

  • 1. codecentric AG Dusan Zamurovic A pattern discussion
  • 2. codecentric AG  Singleton pattern  things we sometimes forget  Dependency injection / Inversion of Control  Paired with Singleton  Example without third party library TOPICS
  • 3. codecentric AG  What Singleton pattern does?  Implementation examples  Wrong implementations  Implementations that look okay  Right implementations Singleton
  • 4. codecentric AG Singleton 01 public class Singleton01 { // TODO Make this class final? private static Singleton01 instance = null; private Singleton01() { // Private constructor prevents instantiation, // but also prevents sub-classing. } public static Singleton01 getInstance() { if (instance == null) { instance = new Singleton01(); } return instance; } }
  • 5. codecentric AG Singleton 02 private static Singleton02 instance = null; public static Singleton02 getInstance() { if (instance == null) { simulateMultiThreadEnvironment(); instance = new Singleton02(); } return instance; } // Not synchronized, not thread safe.
  • 6. codecentric AG Singleton 03 private static Singleton03 instance = null; public synchronized static Singleton03 getInstance() { if (instance == null) { simulateMultiThreadEnvironment(); instance = new Singleton03(); } return instance; } // Synchronized, thread safe.
  • 7. codecentric AG Singleton 04 private static Singleton04 instance = null; public static Singleton04 getInstance() { if (instance == null) { synchronized (Singleton04.class) { simulateMultiThreadEnvironment(); instance = new Singleton04(); } } return instance; } // Synchronized, performance optimization, not thread safe.
  • 8. codecentric AG Singleton 05 private static Singleton05 instance = null; public static Singleton05 getInstance() { if (instance == null) { synchronized (Singleton05.class) { if (instance == null) { instance = new Singleton05(); } } } return instance; } // Double-checked locking – doesn’t work prior to Java 1.5.
  • 9. codecentric AG Singleton 06 private static final Singleton06 INSTANCE = new Singleton06(); public static Singleton06 getInstance() { return INSTANCE; } // Eager instantiating of the class. This works. // What about serialization/deserialization?
  • 10. codecentric AG Singleton 06 Serializable public class Singleton06 implements Serializable { private static final Singleton06 INSTANCE = new Singleton06(); public static Singleton06 getInstance() { return INSTANCE; } } protected Object readResolve() { return getInstance(); }
  • 11. codecentric AG Singleton 07 public enum Singleton07 { INSTANCE; } // What about serialization/deserialization? // What about reflection?
  • 12. codecentric AG  What is DI / IoC?  Implementation example  No third party library Dependency Injection / Inversion of Control
  • 13. codecentric AG Dependency Injection / Inversion of Control @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Component { } @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Inject { } // @Component is used to mark a class – a thing to inject. // @Inject is used to mark a field – a place to inject.
  • 14. codecentric AG Dependency Injection / Inversion of Control @Component public class Controller { @Inject private ManageCapable manager; … } @Component public class Manager implements ManageCapable { @Inject private Repository repository; … }
  • 15. codecentric AG Dependency Injection / Inversion of Control @Component public class Repository { public Resourcable save(Resourcable aResource) { // Here we "persist" the given resource // and return it like we really did it. return aResource; } }
  • 16. codecentric AG Dependency Injection / Inversion of Control public class PackageScanner { … } public class ClassScanner { … } public class DependencyInjectionManager { … } // https://github.com/dzamurovic/meetup_singleton.git
  • 17. codecentric AG Dependency Injection / Inversion of Control public synchronized void run() throws Exception { if (initialized) { return; } // Find classes annotated with @Component. List<Class> components = packageScanner.findAnnotatedClasses( "rs.codecentric.meetup.diioc.example", Component.class); // For each component... for (Class component : components) { Class definingClass = classScanner.getDefiningClass(component); // ... check if its instance already exists... if (!graph.containsKey(definingClass)) { // ... and instantiate it, if it doesn't. String className = component.getName(); graph.put(definingClass, Class.forName(component.getName()).newInstance()); } } }
  • 18. codecentric AG Dependency Injection / Inversion of Control // For each object that is created... for (Iterator<Class> classIterator = graph.keySet().iterator(); classIterator.hasNext();) { Class definingClass = classIterator.next(); Object object = graph.get(definingClass); // ... find dependencies it needs, ... for (Field f : classScanner.findAnnotatedFields(object.getClass(), Inject.class)) { if (!graph.containsKey(f.getType())) { // ... throw an error if a dependency cannot be satisfied, ... } // ... or set a value of the dependency. Object dependency = graph.get(f.getType()); f.set(object, dependency); } } initialized = true; }
  • 19. codecentric AG Dependency Injection / Inversion of Control public static void main(String args[]) throws Exception { final DependencyInjectionManager diManager = DependencyInjectionManager.getInstance(); Thread t1 = new DependencyInjectionThread("DI-thread-0", diManager); Thread t2 = … t1.start(); t2.st… t1.join(); t2.j… diManager.describeDependencyGraph(); }

Hinweis der Redaktion

  1. 1. Thread A notices that the value is not initialized, so it obtains the lock and begins to initialize the value. 2. The code generated by the compiler is allowed to update the shared variable to point to a partially constructed object before A has finished performing the initialization. 3. Thread B notices that the shared variable has been initialized (or so it appears), and returns its value. Because thread B believes the value is already initialized, it does not acquire the lock. If B uses the object before all of the initialization done by A is seen by B the program will likely crash.