Паттерн Observer
This commit is contained in:
parent
9f5a0055f3
commit
49ef151e63
|
|
@ -210,3 +210,55 @@ class MazeSolver:
|
||||||
algorithm=self.strategy.__class__.__name__
|
algorithm=self.strategy.__class__.__name__
|
||||||
)
|
)
|
||||||
return path, stats
|
return path, stats
|
||||||
|
|
||||||
|
class Observer(ABC):
|
||||||
|
@abstractmethod
|
||||||
|
def update(self, event_type, data=None):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ConsoleLogger(Observer):
|
||||||
|
def update(self, event_type, data=None):
|
||||||
|
if event_type == "search_start":
|
||||||
|
print(f"[LOG] Поиск пути начат")
|
||||||
|
elif event_type == "path_found":
|
||||||
|
print(f"[LOG] Путь найден! Длина: {data}")
|
||||||
|
elif event_type == "no_path":
|
||||||
|
print("[LOG] Путь не найден")
|
||||||
|
elif event_type == "step":
|
||||||
|
print(f"[LOG] Шаг: {data}")
|
||||||
|
|
||||||
|
|
||||||
|
class MazeSolverWithObserver(MazeSolver):
|
||||||
|
def __init__(self, maze, strategy, observers=None):
|
||||||
|
super().__init__(maze, strategy)
|
||||||
|
self.observers = observers if observers else []
|
||||||
|
|
||||||
|
def attach(self, observer):
|
||||||
|
self.observers.append(observer)
|
||||||
|
|
||||||
|
def detach(self, observer):
|
||||||
|
self.observers.remove(observer)
|
||||||
|
|
||||||
|
def notify(self, event_type, data=None):
|
||||||
|
for obs in self.observers:
|
||||||
|
obs.update(event_type, data)
|
||||||
|
|
||||||
|
def solve(self):
|
||||||
|
if self.maze.start is None or self.maze.exit is None:
|
||||||
|
raise ValueError("Лабиринт не имеет старта или выхода")
|
||||||
|
self.notify("search_start")
|
||||||
|
start_time = time.perf_counter()
|
||||||
|
path, visited = self.strategy.find_path(self.maze, self.maze.start, self.maze.exit)
|
||||||
|
end_time = time.perf_counter()
|
||||||
|
if path:
|
||||||
|
self.notify("path_found", len(path))
|
||||||
|
else:
|
||||||
|
self.notify("no_path")
|
||||||
|
stats = SearchStats(
|
||||||
|
time_ms=(end_time - start_time) * 1000,
|
||||||
|
visited_cells=visited,
|
||||||
|
path_length=len(path),
|
||||||
|
algorithm=self.strategy.__class__.__name__
|
||||||
|
)
|
||||||
|
return path, stats
|
||||||
Loading…
Reference in New Issue
Block a user