Το μοτίβο Singleton (pattern)

By tgalanis , 24 September 2023
Singleton pattern Swift Xcode
// Singleton

class Database {
    static let instance = Database()
    private init() {}
}

Το singleton pattern (μοτίβο) είναι ένας τρόπος να βεβαιωθούμε ότι μια κλάση έχει μόνο ένα instance (ύπαρξη) και παρέχει ένα και μοναδικό τρόπο για να αποκτήσουμε πρόσβαση σε αυτή.

Το μοτίβο καθορίζει ότι η ίδια η κλάση πρέπει να είναι υπεύθυνη για να ελέγχει την μοναδικότητα της ύπαρξης της.

Επιπλέον πρέπει να εξασφαλίσει ότι κανένα άλλο instance δεν θα παρέμβει στην δημιουργία νέων objects και να παρέχει διαφορετικό τρόπο για να αποκτήσουμε πρόσβαση σε αυτή το μοναδικό instance της κλάσσης.τα 

Τα παρακάτω δεν είναι Singleton

// Not Singleton, this is singleton with "s"
// privivate initializer is missing

class Database {
    static let instance = Database()
}


// Global mutable shared state
// instanse referenced as "static var" instead of "static let"

class Database {
    static var instance = Database()
}

If you have any questions, comments or corrections regarding the article, don't hesitate to write them in the comments below.

Do you want us to dedicate the next one to you?

If you are having difficulty at any point (especially if you are interested in starting with programming), write in the comments the topic you want us to write about and we will dedicate it to you!

Comments