🍪 Privacy & Transparency

We and our partners use cookies to Store and/or access information on a device. We and our partners use data for Personalised ads and content, ad and content measurement, audience insights and product development. An example of data being processed may be a unique identifier stored in a cookie. Some of our partners may process your data as a part of their legitimate business interest without asking for consent. To view the purposes they believe they have legitimate interest for, or to object to this data processing use the vendor list link below. The consent submitted will only be used for data processing originating from this website. If you would like to change your settings or withdraw consent at any time, the link to do so is in our privacy policy accessible from our home page..

Vendor List | Privacy Policy
Skip to content

Technik Blog

Programmieren | Arduino | ESP32 | MicroPython | Python | Raspberry PI

Menu
  • Projekte
    • LED’s
    • Servo & Schrittmotoren
    • Sound
    • LCD’s
    • Kommunikation
    • Sicherheit
    • Weekend Project
  • Arduino
    • Tutorials
    • ProMini
      • Anschließen & Programmieren
    • Nano
      • Arduino Nano – Übersicht
    • UNO
      • Übersicht
    • MEGA 2560
      • Übersicht
    • Leonardo
      • Übersicht
    • NodeMCU
      • NodeMCU – “Einer für (fast) Alles!”
    • Lilypad
      • Arduino: Lilypad “Jetzt Geht’s Rund!”
    • WEMOS
      • WEMOS D1 – Arduino UNO kompatibles Board mit ESP8266 Chip
      • WEMOS D1 Mini – Übersicht
      • Wemos D1 mini Shields
    • STM32x
      • STM32F103C8T6 – Übersicht
    • Maker UNO
      • Maker UNO – Überblick und Test
    • ATTiny85
      • Mini Arduino mit ATTiny85 Chip
      • ATtiny85 mit dem Arduino UNO beschreiben
  • Android
  • Über mich
  • DeutschDeutsch
  • EnglishEnglish
Menu

Java: Singleton Pattern

Posted on 24. November 20162. Mai 2023 by Stefan Draeger

Das wohl einfachste Entwurfsmuster (Design Pattern) ist das Singleton Pattern.

  • Erläuterung zum Singleton Pattern
  • Beispiel 1
  • Beispiel 2
  • Beispiel 3
  • Zusammenfassung

Erläuterung zum Singleton Pattern

Durch die Verwendung des Singleton Pattern wird sichergestellt, dass nur ein Objekt existiert und global verfügbar ist. D.h. es wird einmalig ein Objekt erzeugt und alle anderen verwenden dieses wieder.

Beispiel 1

Dieses Beispiel zeigt die reine Lehre des Singleton Pattern, wie es auf und in diversen Seiten und Büchern präsentiert wird.

public class SingletonSimple {

	private static SingletonSimple SINGLETON;
	
	private String name = SingletonConstants.UNDEFINED;
	
	private SingletonSimple(){
           //Do some stuff here.
        }
	
	public static SingletonSimple getInstance(){
		if(SINGLETON == null){
			SINGLETON = new SingletonSimple();
		}
	   return SINGLETON;
	}
	
	public String getName() {return name;}
	
	public void setName(String name) {this.name = name;}
}

Bei diesem Beispiel wird dem geschulten Entwickler auffallen, dass dieses nicht Threadsafe ist, aber dazu später mehr.

Beispiel 2

Dieses Beispiel zeigt das Beispiel 1 jedoch als Threadsafe Variante. Durch den Synchronized Block wird sichergestellt, dass nur 1 Thread auf die Erzeugung eines neuen Objektes zugreifen kann.

public class SingletonSynchronize {

	private static SingletonSynchronize SINGLETON;
	
	private String name = SingletonConstants.UNDEFINED;
	
	private SingletonSynchronize(){ 
		//Do some stuff here. 
	}
	
	public static SingletonSynchronize getInstance(){
		if(SINGLETON == null){
			synchronized (SingletonSynchronize.class) {
				if(SINGLETON == null){
					SINGLETON = new SingletonSynchronize();
				}
			}
		}
		return SINGLETON;
	}
	
	public String getName() { return name; }
	
	public void setName(String name) { this.name = name; }
}

Gut zu erkennen ist der Double Check-in der Methode „getInstance()“ dieser ist notwendig, da die Verwendung von „synchronized“ sehr viel Ressourcen benötigt.

Hier ein „kleiner“ Testfall, welcher das Verhalten verdeutlichen soll.

public class SingletonSynchronizedResourceTest {
	
	@Test
	public void testSynchronizeDoubleCheckRessource(){
		long timestampBefore = System.currentTimeMillis();
		SingletonSynchronizedDoubleCheck singletonSyncronize; 
		for(Integer i=0;i<Integer.MAX_VALUE;i++){
			singletonSyncronize = SingletonSynchronizedDoubleCheck.getInstance();
		}
		long timestampAfter = System.currentTimeMillis();
		printTime(timestampBefore, timestampAfter, "SingletonSynchronizedDoubleCheck");
	}
	
	@Test
	public void testSynchronizeNonDoubleCheckRessource(){
		long timestampBefore = System.currentTimeMillis();
		SingletonSynchronizedNonDoubleCheck singletonSyncronize; 
		for(Integer i=0;i<Integer.MAX_VALUE;i++){
			singletonSyncronize = SingletonSynchronizedNonDoubleCheck.getInstance();
		}
		long timestampAfter = System.currentTimeMillis();
		printTime(timestampBefore, timestampAfter, "SingletonSynchronizedNonDoubleCheck");
	}
	
	private void printTime(long before, long after, String text){
		System.out.println(String.format("Zeit für %s:\t %d ms",text, (after-before)));
	}

	private static class SingletonSynchronizedDoubleCheck {

		private static SingletonSynchronizedDoubleCheck SINGLETON;

		private SingletonSynchronizedDoubleCheck() {
		}

		public static SingletonSynchronizedDoubleCheck getInstance() {
			if (SINGLETON == null) {
				synchronized (SingletonSynchronize.class) {
					if (SINGLETON == null) {
						SINGLETON = new SingletonSynchronizedDoubleCheck();
					}
				}
			}
			return SINGLETON;
		}

	}

	private static class SingletonSynchronizedNonDoubleCheck {

		private static SingletonSynchronizedNonDoubleCheck SINGLETON;

		private SingletonSynchronizedNonDoubleCheck() {
		}

		public static SingletonSynchronizedNonDoubleCheck getInstance() {
			synchronized (SingletonSynchronize.class) {
				if (SINGLETON == null) {
					SINGLETON = new SingletonSynchronizedNonDoubleCheck();
				}
			}
			return SINGLETON;
		}

	}
}

Dieser JUnit Test erzeugt den Output auf der Konsole, wo man deutlich den Zeitunterschied erkennen kann:

Es ist deutlich erkennbar, dass der Testfall, welcher ohne DoubleCheck arbeitet, länger dauert als mit DoubleCheck.

Beispiel 3

Seit der Java Version 5 gibt es das Keyword „enum“. Ein „enum“ erzeugt pro Enumarationskonstante eine Instanz.
Dieses ist per Definition bereits ein Singleton.

public enum SingletonEnum {

	SINGLETON;

	protected static String myName = SingletonConstants.UNDEFINED;

	private SingletonEnum() {}

	public String getMyName() {return myName;}

	public void setMyName(String myName) { SingletonEnum.myName = myName; }

}

Diese Version des Singleton Patterns wird als „bulletprof version“ bezeichnet da es Threadsafe und vorallem einfach zu verwenden ist.

Zusammenfassung

Es wurden 3 Beispiele für die Implementierung des Singleton Patterns aufgezeigt, wobei Beispiel 1 sehr verbreitet ist, aber durch die heutige Technik des verteilten Rechnens bzw. 3 TIER Umgebungen nicht mehr verwendet werden sollte. Beispiel 2 zeigt durch die Verwendung von Synchronized eine gute Möglichkeit auf dieses Pattern in einer Mehrschicht Architektur zu verwenden, ohne dabei an Performance einzubüßen. Das letzte Beispiel (3) zeigt die zurzeit als „bulletprof version“ zu Recht bezeichnete Lösung.

Schreibe einen Kommentar Antworten abbrechen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Kategorien

Tools

  • 8×8 LED Matrix Tool
  • 8×16 LED Matrix Modul von Keyestudio
  • 16×16 LED Matrix – Generator
  • Widerstandsrechner
  • Rechner für Strom & Widerstände
  • ASCII Tabelle

Meta

  • Videothek
  • Impressum
  • Datenschutzerklärung
  • Disclaimer
  • Kontakt
  • Cookie-Richtlinie (EU)

Links

Blogverzeichnis Bloggerei.de Blogverzeichnis TopBlogs.de das Original - Blogverzeichnis | Blog Top Liste Blogverzeichnis trusted-blogs.com
©2023 Technik Blog | Built using WordPress and Responsive Blogily theme by Superb