MST

星途 面试题库

面试题:Python组合模式在复杂项目中的应用场景

假设你正在参与一个大型Python项目,该项目涉及文件系统的操作模拟,包括目录和文件的管理,要求使用组合模式来设计相关类结构。请描述你的设计思路,并给出关键代码片段。
35.4万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 抽象组件类:定义一个抽象基类,作为文件和目录的共同接口,包含操作文件系统对象的通用方法,如获取名称、添加子对象、删除子对象等。
  2. 文件类:继承自抽象组件类,代表文件对象,实现抽象基类中的方法。由于文件没有子对象,添加和删除子对象方法可以抛出不支持操作的异常。
  3. 目录类:继承自抽象组件类,代表目录对象,维护一个子对象列表,实现添加、删除子对象以及遍历子对象等方法。

关键代码片段

from abc import ABC, abstractmethod


class FileSystemComponent(ABC):
    def __init__(self, name):
        self.name = name

    @abstractmethod
    def get_name(self):
        pass

    @abstractmethod
    def add(self, component):
        pass

    @abstractmethod
    def remove(self, component):
        pass

    @abstractmethod
    def display(self, depth):
        pass


class File(FileSystemComponent):
    def get_name(self):
        return self.name

    def add(self, component):
        raise NotImplementedError("文件不能添加子对象")

    def remove(self, component):
        raise NotImplementedError("文件不能删除子对象")

    def display(self, depth):
        print('-' * depth + self.name)


class Directory(FileSystemComponent):
    def __init__(self, name):
        super().__init__(name)
        self.children = []

    def get_name(self):
        return self.name

    def add(self, component):
        self.children.append(component)

    def remove(self, component):
        if component in self.children:
            self.children.remove(component)

    def display(self, depth):
        print('-' * depth + self.name)
        for child in self.children:
            child.display(depth + 2)


你可以这样使用这些类:

# 创建文件和目录
root = Directory("root")
dir1 = Directory("dir1")
file1 = File("file1.txt")
file2 = File("file2.txt")

# 构建文件系统结构
root.add(dir1)
dir1.add(file1)
root.add(file2)

# 显示文件系统结构
root.display(0)