Singleton
This commit is contained in:
parent
14c9a2a54b
commit
581eb7ce83
4 changed files with 71 additions and 0 deletions
24
game.py
Normal file
24
game.py
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
'Beispielcode für einen Singelton'
|
||||||
|
from singleton import Singleton
|
||||||
|
|
||||||
|
|
||||||
|
class Game(metaclass=Singleton):
|
||||||
|
'Beispielklasse für einen Singelton. Kann nur seinen Namen merken.'
|
||||||
|
_name = 'New unnamed Game'
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def set_name(self, name) -> None:
|
||||||
|
'Setzt Namen vom Spiel'
|
||||||
|
self._name: str = name
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return self.get_name()
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return f'game: {self.get_name()}'
|
||||||
|
|
||||||
|
def get_name(self) -> str:
|
||||||
|
'Gibt Namen vom Spiel'
|
||||||
|
return self._name
|
28
main.py
Normal file
28
main.py
Normal file
|
@ -0,0 +1,28 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: UTF-8 -*-
|
||||||
|
#
|
||||||
|
# main.py
|
||||||
|
#
|
||||||
|
# Copyright 2023 Beat Jäckle <beat@git.jdmweb2.ch>
|
||||||
|
'Beispiel um den Einsatz von einem Singleton zu zeigen.'
|
||||||
|
from test import print_new_game
|
||||||
|
from game import Game
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
'''
|
||||||
|
Erstellt ein Game x und ruft unabhängig eine Funktion auf,
|
||||||
|
welche ein neues Game y erstellt.
|
||||||
|
Der Name vom neuen Game ist der Name des Games x.
|
||||||
|
'''
|
||||||
|
x_game = Game()
|
||||||
|
print(x_game)
|
||||||
|
x_game.set_name('Spiel X')
|
||||||
|
print(x_game)
|
||||||
|
print_new_game()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import sys
|
||||||
|
sys.exit(main())
|
11
singleton.py
Normal file
11
singleton.py
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
'Demo Singleton Code von https://stackoverflow.com/a/6798042/9773263'
|
||||||
|
|
||||||
|
|
||||||
|
class Singleton(type):
|
||||||
|
'Singelton von agf, Lizenz: CC BY-SA 2.5'
|
||||||
|
_instances = {}
|
||||||
|
|
||||||
|
def __call__(cls, *args, **kwargs):
|
||||||
|
if cls not in cls._instances:
|
||||||
|
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
|
||||||
|
return cls._instances[cls]
|
8
test.py
Normal file
8
test.py
Normal file
|
@ -0,0 +1,8 @@
|
||||||
|
'Erstellt ein neues Game. Wie wird es wohl heissen?'
|
||||||
|
from game import Game
|
||||||
|
|
||||||
|
|
||||||
|
def print_new_game():
|
||||||
|
'Erstellt ein neues Game und printet den Namen.'
|
||||||
|
y_game = Game()
|
||||||
|
print(y_game)
|
Loading…
Reference in a new issue