0% ont trouvé ce document utile (0 vote)
30 vues6 pages

Comprendre le patron Singleton

singleton design patterns cours complet francais

Transféré par

stepbysteptoUranus
Copyright
© All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd
0% ont trouvé ce document utile (0 vote)
30 vues6 pages

Comprendre le patron Singleton

singleton design patterns cours complet francais

Transféré par

stepbysteptoUranus
Copyright
© All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd

Le patron

Singleton

Cours DP– Mme Sameh HBAIEB


Le patron Singleton: Présentation
 L’objectif du patron Singleton est de garantir qu'une classe ne possède
qu'une seule et unique instance, et de fournir un point d’accès global à
celle‐ci.
 Indications d’utilisation
 Il doit y avoir exactement une instance d’une classe ;
 cette instance est accessible globalement ;
 Exemples d’utilisation :
 Fenêtre principale d’une IHM
 Accès à un fichier de configuration
 Accès à une base de données

Cours DP– Mme Sameh HBAIEB


Le patron Singleton:l Principe
Comment pouvez‐vous empêcher d’autres développeurs de créer de
nouvelles instances de votre classe?

Créer un seul constructeur avec un accès privé

Cours DP– Mme Sameh HBAIEB


Modèle de représentation du patron Singleton
 Etapes :
 Rendre privé le constructeur,
 Construire une instance privée de la classe
comme attribut statique de la classe,
 Fournir une méthode publique d’accès à
cette instance.

Cours DP– Mme Sameh HBAIEB


Exemple d’implémentation du patron Singleton

public class SingleObject {

//create an object of SingleObject


private static SingleObject instance = new SingleObject();

//make the constructor private so that this class cannot be


//instantiated
private SingleObject(){}

//Get the only object available


public static SingleObject getInstance(){
return instance;
}
}

Cours DP– Mme Sameh HBAIEB


Exercice d’application
1. Ecrire un programme java qui permet de créer une instance de Base de
données unique.
Cette base de données possède deux attributs « record » (n°de
l’enregistrement courant) et « name » (nom de la BdD). Une méthode,
«editRecord », qui permet d’éditer un enregistrement dans la BDD (en affichant
seulement que l’enregistrement subit une opération de modification) et une
méthode « getName », qui retourne le nom de la BDD.
2. Testez dans un programme l’unicité de la BdD.

Cours DP– Mme Sameh HBAIEB

Common questions

Alimenté par l’IA

Testing the uniqueness of a Singleton instance in Java can be done by attempting to retrieve the instance multiple times and verifying that they reference the same memory address. This can be implemented using assertions to check that `SingleObject.getInstance()` returns the same object on multiple calls, confirming its uniqueness. For example: `assert SingleObject.getInstance() == SingleObject.getInstance();` .

The Singleton pattern may be inappropriate when multiple instances of a class are needed or in highly multithreaded environments where lazy initialization is required for better resource management. Moreover, it can introduce global state into an application, potentially leading to difficulties in testing and less clear code dependencies .

To implement a Singleton class in Java: 1) Make the constructor private to prevent external instantiation. 2) Create a private static variable of the class type to hold the singleton instance. 3) Provide a public static method to return the unique instance. Code snippet: `public class SingleObject { private static SingleObject instance = new SingleObject(); private SingleObject(){} public static SingleObject getInstance(){ return instance; } }` .

Yes, the Singleton pattern can be used for early initialization by creating the instance at the time of class loading. This is achieved by declaring and initializing the static instance variable at the class level. This ensures the instance is created even before any method in the class is called. This approach guarantees thread-safety as the class loader mechanism ensures that the instantiation occurs only once .

The Singleton design pattern ensures that a class has only one instance and provides global access to that instance. This is particularly beneficial in scenarios where exactly one object is sufficient to coordinate actions across the system such as accessing a configuration file, connecting to a database, or managing the main window of an application .

The Singleton pattern can degrade software maintainability by introducing global state and tight coupling, making it challenging to modify without impacting dependent components. To mitigate this, developers should ensure that the Singleton is well-documented, and consider alternative designs like dependency injection, which provides more flexibility and easier testing environments, thus maintaining the codebase's maintainability .

The Singleton pattern aligns with encapsulation by controlling the instantiation and access to the instance using a private constructor and a public static method. This restricts the visibility and modification of the class's internal data, maintaining control over how and when an instance is created and accessed. It encapsulates the instance within the class and provides a controlled access point .

The Singleton design pattern restricts class instantiation by making the constructor private, preventing the creation of instances from outside the class. It also defines a static method that returns a single instance of the class. This instance is stored in a private static variable within the class, effectively limiting instantiation to a single object .

The Singleton pattern provides global access to an instance through a public static method that returns the singleton instance. This feature allows any part of the program to access the unique instance. However, global access can lead to tight coupling between classes, making it harder to refactor or test the code since different parts of the program might depend on the particular Singleton instance's state .

In a multithreaded environment, the Singleton pattern may face challenges with concurrent access where multiple instances could be created if threads access the instance creation method at the same time. This can be addressed by implementing synchronized methods, using a `volatile` keyword to ensure visibility of changes across threads, or employing a double-checked locking mechanism to ensure only one instance is created .

Vous aimerez peut-être aussi