|
| 1 | +""" |
| 2 | +GRASP Low Coupling - Game System |
| 3 | +
|
| 4 | +>>> # Test ScoreService |
| 5 | +>>> service = ScoreService() |
| 6 | +>>> service.save_score("player1", 100) |
| 7 | +'Saved score 100 for player1' |
| 8 | +
|
| 9 | +>>> # Test Game with ScoreService (low coupling) |
| 10 | +>>> game = Game(service) |
| 11 | +>>> game.finish_game("Alice", 150) |
| 12 | +'Game finished. Saved score 150 for Alice' |
| 13 | +""" |
| 14 | + |
| 15 | + |
| 16 | +class Database: |
| 17 | + """Konkretna implementacja bazy danych""" |
| 18 | + |
| 19 | + def connect(self) -> str: |
| 20 | + return "Connected to database" |
| 21 | + |
| 22 | + def save(self, player: str, score: int) -> str: |
| 23 | + return f"Saved score {score} for {player}" |
| 24 | + |
| 25 | + |
| 26 | +# TODO: Zaimplementuj ScoreService |
| 27 | +# Klasa pośrednicząca między Game a bazą danych (redukuje sprzężenie) |
| 28 | +# Metoda save_score(player, score) zwraca: "Saved score {score} for {player}" |
| 29 | + |
| 30 | +class ScoreService: |
| 31 | + def __init__(self): |
| 32 | + self.database = Database() |
| 33 | + |
| 34 | + def save_score(self, player: str, score: int) -> str: |
| 35 | + """Pośrednik - izoluje Game od Database""" |
| 36 | + self.database.connect() |
| 37 | + return self.database.save(player, score) |
| 38 | + |
| 39 | + |
| 40 | +# TODO: Zaimplementuj Game |
| 41 | +# Przyjmuje score_service: ScoreService w konstruktorze (dependency injection) |
| 42 | +# Metoda finish_game(player, score): |
| 43 | +# - Wywołuje score_service.save_score(player, score) |
| 44 | +# - Zwraca "Game finished. {wynik z save_score}" |
| 45 | +# |
| 46 | +# Low Coupling: Game nie zna Database, tylko ScoreService (pośrednik) |
| 47 | + |
| 48 | +class Game: |
| 49 | + def __init__(self, score_service: ScoreService): |
| 50 | + """Dependency Injection - redukuje sprzężenie""" |
| 51 | + self.score_service = score_service |
| 52 | + |
| 53 | + def finish_game(self, player: str, score: int) -> str: |
| 54 | + """Game używa tylko ScoreService, nie zna Database""" |
| 55 | + result = self.score_service.save_score(player, score) |
| 56 | + return f"Game finished. {result}" |
| 57 | + |
| 58 | + |
| 59 | +# GRASP Low Coupling: |
| 60 | +# Minimalizuj zależności między klasami |
| 61 | +# |
| 62 | +# Silne sprzężenie ❌: |
| 63 | +# Game → Database (bezpośrednia zależność) |
| 64 | +# |
| 65 | +# Luźne sprzężenie ✅: |
| 66 | +# Game → ScoreService → Database (pośrednik) |
| 67 | +# |
| 68 | +# Korzyść: Zmiana Database nie wpływa na Game |
| 69 | + |
| 70 | + |
| 71 | +# Przykład użycia |
| 72 | +if __name__ == "__main__": |
| 73 | + service = ScoreService() |
| 74 | + game = Game(service) |
| 75 | + print(game.finish_game("Alice", 150)) |
0 commit comments