Zum Hauptinhalt springen
Echtzeit-Radar & Feeds
Alle RSS Feeds ➔
👥 Community & Social
••
IT NachrichtenMicrosoft puts Brad Smith in charge of communications(25.09.2026 um 00:08 Uhr)
••
IT Nachrichten25. September(25.09.2026 um 00:05 Uhr)
•
IT NachrichtenCI-Solution GmbH von Crossware übernommen(25.09.2026 um 00:01 Uhr)
•
IT NachrichtenInsta360 GO Ultra erhält KI-Sprachassistenten mit Gemini(24.09.2026 um 21:30 Uhr)
••
AI & KI NachrichtenMaryland Governor Draws New Boundaries for Data Centers(25.09.2026 um 00:04 Uhr)
••••
IT NachrichtenMicrosoft puts Brad Smith in charge of communications(25.09.2026 um 00:08 Uhr)
••
IT Nachrichten25. September(25.09.2026 um 00:05 Uhr)
•
IT NachrichtenCI-Solution GmbH von Crossware übernommen(25.09.2026 um 00:01 Uhr)
•
IT NachrichtenInsta360 GO Ultra erhält KI-Sprachassistenten mit Gemini(24.09.2026 um 21:30 Uhr)
••
AI & KI NachrichtenMaryland Governor Draws New Boundaries for Data Centers(25.09.2026 um 00:04 Uhr)
••
Intelligence View
⚡ tsecurity.de Intelligence

Design Pattern - Singleton

O objetivo deste padrão é bem simples, garantir que apenas uma instância de uma determinada classe seja criada. Simples não?! Após padrões um tanto quanto confusos e complexos, parece até pegadinha mas é fato, realmente é simples. Mas qua…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

O objetivo deste padrão é bem simples, garantir que apenas uma instância de uma determinada classe seja criada.



Simples não?! Após padrões um tanto quanto confusos e complexos, parece até pegadinha mas é fato, realmente é simples. Mas quando isso pode ser aplicado?! Um exemplo comum são as situações de conexões com banco, normalmente não queremos ter N fontes de verdades sobre os dados, o que poderia ocasionar situações de conflito entre essas instâncias.




Não vou me extender neste padrão, ele realmente é simples, deixarei algumas recomendações no final caso queira saber mais!




Ótimo, você já entendeu que o objetivo é criar apenas uma instância, mas como podemos fazer isso?! Algumas linguagens como C# permitem que "marquemos" determinados serviços como singleton quando realizamos a injeção de dependências, então talvez você já tenha visto algo como isso:





.AddSingleton<Interface, Class>()







Mas aqui quero falar um pouco mais sobre a ótica de criarmos uma classe que só possa ter uma instância e não sobre um serviço em si. Pensemos no seguinte, você está construindo um jogo de futebol, neste jogo teremos vários objetos que teremos um ou mais, como jogadores de linha, goleiros, bandeirinhas, mas teremos apenas uma objeto bola, apenas um objeto juíz...



Primeiro vamos criar nossa classe de interesse




public class Ball
{
    private static Ball instance;
    public string ImagePath { get; set; }
    public string Weight { get; set; }
    public double ElasticCoefficient { get; set; }

    private Ball() { }

    public static Ball GetInstance()
    {
instance ??= new Ball(); // só é instanciado se instace é nula
        return instance;
    }
}







Agora vamos verificar se tudo ocorreu bem




using SingletonFootball;

var b1 = Ball.GetInstance();
var b2 = Ball.GetInstance();

if (b1 == b2)
    Console.WriteLine("A mesma instância foi atribuída aos dois objetos");
else
    Console.WriteLine("Instância diferentes foram atribuídas");






No console veremos:




A mesma instância foi atribuída aos dois objetos






Ótimo, funcionou!!! Mas aqui mora uma pegadinha, se por algum motivo estivermos trabalhando com Threads, teremos a possibilidade de várias rotinas acessarem simultaneamente obtendo várias instância, para corrigir isso precisamos realizar pequenas modificações em nosso código.



Para isso vamos implementar a classe Referee utilizando uma instrução chamada lock. A ideia é que a primeira instância a chave, irá bloquear que outras possíveis instâncias sejam iniciadas.




public class Referee
{
    private static Referee instance;
    public string Name { get; set; }

    private static readonly object _lock = new object();

    private Referee(){ }

    public static Referee GetInstance(string value)
    {
        if (instance == null)
        {
            lock (_lock)
            {
                if (instance == null)
                {
                    instance = new Referee();
                    instance.Name = value;
                }
            }
        }
        return instance;
    }
}






Agora vamos testar o que implementamos




Thread process1 = new Thread(() => {
    TestSingleton("George");
});

Thread process2 = new Thread(() => {
    TestSingleton("Hamilton");
});

process1.Start();
process2.Start();

process1.Join();
process2.Join();

void TestSingleton(string value)
{
    Referee Referee = Referee.GetInstance(value);
    Console.WriteLine(Referee.Name);
}






Na saída teremos então:




George
George






Desse modo garantiremos que apenas uma instância será criada, mesmo quando utilizarmos threads para execução de tarefas.






Repositório GIT



Design Patterns






Materiais de Estudo



Estamos chegando ao fim do nosso artigo e queria deixar alguns materiais que usei para estudar esse padrão de software:



Refactoring Guru



Dofactory



Higor Diego - Padrão - Singleton



Balta - AddTransit, AddScopped, AddSingleton



Um pouco sobre a instrução lock

SOC Incident Playbook: Vulnerability Remediation & Verification
Syntax validiert (0 Fehler)
title: Detect Exploitation - Design Pattern - Singleton
id: 25b9c382-5b58-4fa7-b9a1-9da741fb0705
status: experimental
description: Automatisch generierte SIEM-Erkennungsregel basierend auf CTI Intelligence
references:
  - https://tsecurity.de/
author: iShareStuff CTI Automated Detection Engine
date: 2026-09-25
logsource:
  category: network_connection
  product: any
detection:
  selection:
      CommandLine|contains:
        - 'exploit'
  condition: selection
falsepositives:
  - Legitime administrative Zugriffe oder Penetrationstests
level: high
tags:
  - attack.initial_access
Syntax validiert (0 Fehler)
rule CTI_Threat_Indicator {
    meta:
        author = "iShareStuff CTI Automated Detection Engine"
        date = "2026-09-25"
        description = "YARA Signature for "
    strings:
        $str = "Design Pattern - Singleton" ascii wide
    condition:
        any of them
}
Syntax validiert (0 Fehler)
index=security sourcetype IN ("cisco:asa", "pan:traffic", "zeek_conn", "suricata", "WinEventLog:Security")
("Design Pattern - Singleton")
| stats count earliest(_time) as first_seen latest(_time) as last_seen by src_ip, dest_ip, dest_host, signature
| eval first_seen=strftime(first_seen, "%Y-%m-%d %H:%M:%S"), last_seen=strftime(last_seen, "%Y-%m-%d %H:%M:%S")
| sort - count
Syntax validiert (0 Fehler)
message: "*Design Pattern - Singleton*"
Syntax validiert (0 Fehler)
CommonSecurityLog
| where Message has "Design Pattern - Singleton"
| summarize EventCount = count(), FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated) by SourceIP, DestinationIP, DestinationPort, Activity
| extend DetectionRule = "iShareStuff-CTI-Compiled"
| sort by EventCount desc
🎯
MITRE ATT&CK Matrix Navigator 14 Taktiken
Reconnaissance
-
Resource Development
-
Initial Access
Execution
Persistence
-
Privilege Escalation
Defense Evasion
Credential Access
-
Discovery
-
Lateral Movement
-
Collection
-
Command and Control
Exfiltration
-
Impact
tsecurity.de Cognitive Threat RAG
Fokus-Vektor:

Kognitive Analyse für identifizierte Bedrohung: Erhöhte Bedrohungslage im Bereich Design Pattern - Singleton.... Basierend auf 368k Vektor-Korrelationen werden sofortige Isolationsmaßnahmen für betroffene Endpunkte empfohlen.

🛡️ Angriffsfläche & Exposure

Netzwerk/Remote-Zugriff ohne Vorauthentifizierung möglich.

⚡ Empfohlene Sofortmaßnahmen
  • 1. Perimeter-Inspektion: Relevante Portfreigaben und exponierte Endpunkte unverzüglich scannen.
  • 2. Patch-Applikation: Hersteller-Hotfix einspielen oder betroffene Daemons in isolierte DMZ-Segmente überführen.
  • 3. Telemetrie & EDR-Alerts: Prozessaufrufe und Child-Processes auf anomale Shell-Spawns überwachen.
🔗 Semantisch verwandte Zero-Days MariaDB 11.7 VEC
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Design Pattern - Singleton

Thematisch verwandte Begriffe: Design, Pattern, Singleton · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-82585 | The Botslab G980H dash camera firmware transmits sensitive information o…
Advisory →
tsecurity.de Icon
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel • Rechts: nächster Artikel • unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel TTP ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...
↗ Original-Quelle