Advertisement
adolphuZ

Untitled

Jun 5th, 2024
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.93 KB | None | 0 0
  1. from abc import ABC, abstractmethod
  2. import time
  3. import threading
  4.  
  5. # Interfejs dla usług dostarczających kursy walut
  6. class ExchangeRateService(ABC):
  7.     @abstractmethod
  8.     def get_rate(self):
  9.         pass
  10.  
  11. # Implementacja konkretnej usługi i jej adaptera
  12. class ServiceA:
  13.     def fetch_rate(self):
  14.         # Symulacja pobierania kursu
  15.         return 4.55
  16.  
  17. class ServiceAAdapter(ExchangeRateService):
  18.     def __init__(self, service):
  19.         self.service = service
  20.  
  21.     def get_rate(self):
  22.         return self.service.fetch_rate()
  23.  
  24. class ServiceB:
  25.     def retrieve_rate(self):
  26.         # Symulacja pobierania kursu
  27.         return 4.53
  28.  
  29. class ServiceBAdapter(ExchangeRateService):
  30.     def __init__(self, service):
  31.         self.service = service
  32.  
  33.     def get_rate(self):
  34.         return self.service.retrieve_rate()
  35.  
  36. # Klasa do porównywania kursów i wybierania najlepszego
  37. class CurrencyBuyer:
  38.     def __init__(self, services):
  39.         self.services = services
  40.         self.best_rate = float('inf')
  41.  
  42.     def find_best_rate(self):
  43.         for service in self.services:
  44.             rate = service.get_rate()
  45.             if rate < self.best_rate:
  46.                 self.best_rate = rate
  47.                 print(f"New best rate found: {self.best_rate}")
  48.  
  49. # Funkcja do cyklicznego odczytu kursów
  50. def fetch_rates_periodically(buyer, interval):
  51.     while True:
  52.         buyer.find_best_rate()
  53.         time.sleep(interval)
  54.  
  55. # Testowanie aplikacji
  56. def main():
  57.     service_a = ServiceA()
  58.     service_a_adapter = ServiceAAdapter(service_a)
  59.  
  60.     service_b = ServiceB()
  61.     service_b_adapter = ServiceBAdapter(service_b)
  62.  
  63.     services = [service_a_adapter, service_b_adapter]
  64.     buyer = CurrencyBuyer(services)
  65.  
  66.     # Start periodic rate fetching in a separate thread
  67.     fetch_thread = threading.Thread(target=fetch_rates_periodically, args=(buyer, 10))
  68.     fetch_thread.start()
  69.  
  70. if __name__ == "__main__":
  71.     main()
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement