Adapter
- hivecore.patterns.adapter(adaptee_name: str, **method_map)
Decorator to create an adapter class that adapts an adaptee class.
- Parameters:
adaptee_name (str) – The name of the adaptee class to be used.
method_map (dict) – Keyword arguments mapping methods of the adapter class to methods of the adaptee class.
- Returns:
The decorated class acting as an adapter.
- Return type:
class
Adaptee
- hivecore.patterns.adaptee(name: str | None = None)
Decorator to register a class as an adaptee.
- Parameters:
name (str) – The name of the adaptee (optional).
- Returns:
The decorated class.
- Return type:
class
Example
We create an adaptee class CelsiusTemperatureSensor. For this example, we want to adapt this celsius sensor to both fahrenheit and kelvin.
from hivecore.patterns import adaptee
@adaptee
class CelsiusTemperatureSensor:
def get_temperature(self):
return 25 # Celsius
Creating the Adapter
We define FahrenheitTemperatureSensor and KelvinTemperatureSensor as adapters for the CelsiusTemperatureSensor.
from hivecore.patterns import adapter
def celsius_to_fahrenheit(celsius):
return 9.0 / 5.0 * celsius + 32
@adapter("CelsiusTemperatureSensor", get_temperature="get_temperature")
class FahrenheitTemperatureSensor:
def get_temperature(self):
celsius = self._adaptee.get_temperature()
return celsius_to_fahrenheit(celsius)
@adapter("CelsiusTemperatureSensor", get_temperature="get_temperature")
class KelvinTemperatureSensor:
def get_temperature(self):
celsius = self._adaptee.get_temperature()
return celsius + 273.15
Using the Adapter
# Create adapter objects
fahrenheit_sensor = FahrenheitTemperatureSensor()
kelvin_sensor = KelvinTemperatureSensor()
# Get temperature in different units
print(fahrenheit_sensor.get_temperature())
print(kelvin_sensor.get_temperature())
Output
77.0
298.15