Skip to content

Instantly share code, notes, and snippets.

@albexl
Created January 27, 2023 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save albexl/a1ea8687d7b909196a1a15a5f917db1a to your computer and use it in GitHub Desktop.
Save albexl/a1ea8687d7b909196a1a15a5f917db1a to your computer and use it in GitHub Desktop.
"""Solution using interfaces"""
from abc import ABC, abstractmethod
from enum import Enum
from typing import List
from typing_extensions import Self
class IVisitor(ABC):
"""Base class for the Visitor interface"""
@abstractmethod
def can_access(self, visitors: List[Self]) -> bool:
"""Returns whether or not a visitor is on the list of authorized visitors.
Args:
visitors (List[Self]): Authorized visitors list.
Returns:
bool: `True` if the given visitor is on the list of authorized visitors. `False` otherwise.
"""
class Person(IVisitor):
"""Concrete implementation of a Visitor"""
def __init__(self, id: str, name: str) -> None:
self.id = id
self.name = name
def __str__(self) -> str:
return self.id
def can_access(self, visitors: List[IVisitor]) -> bool:
for visitor in visitors:
if isinstance(visitor, Person) and visitor.id == self.id:
return True
return False
class VehicleType(Enum):
"""Enum class to represent a Vehicle Type"""
AUTO = 1
TRUCK = 2
BUS = 3
class Vehicle(IVisitor):
"""Concrete implementation of a Visitor"""
def __init__(self, license_plate: str, vehicle_type: VehicleType) -> None:
self.license_plate = license_plate
self.vehicle_type = vehicle_type
def __str__(self) -> str:
return self.license_plate
def can_access(self, visitors: List[IVisitor]) -> bool:
for visitor in visitors:
if (
isinstance(visitor, Vehicle)
and visitor.license_plate == self.license_plate
):
return True
return False
class ResearchCenter:
"""Controller class"""
def __init__(self):
self.visitors = []
def add_visitor(self, visitor: IVisitor):
"""Adds a new visitor to the list of visitors.
Args:
visitor (IVisitor): The visitor to be added.
"""
self.visitors.append(visitor)
def verify_access(self, visitor: IVisitor) -> bool:
"""Verifies that the visitor is authorized to enter.
Other checks can be made based on schedules, etc...
Args:
visitor (IVisitor): The visitor to check for access.
Returns:
bool: True if the visitor has access, False otherwise.
"""
return visitor.can_access(self.visitors)
if __name__ == "__main__":
carlos = Person("11111111111", "Carlos")
truck = Vehicle("ABC123", VehicleType.TRUCK)
bus = Vehicle("XYZ789", VehicleType.BUS)
center = ResearchCenter()
center.add_visitor(carlos)
center.add_visitor(truck)
print(center.verify_access(carlos))
print(center.verify_access(truck))
print(center.verify_access(bus))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment