架构师面试题 (2)
发布于: 2020 年 06 月 21 日
请在草稿纸上手写一个单例模式的代码实现

请用组合时间模式编写程序, 打印输出图1的窗口, 窗口组件的树结构如图2所示

Python代码实现
class Component(object):    """组件接口"""    def do_something(self):        raise NotImplementedErrorclass BaseComponent(Component):    """    这个类, 只是为了本练习更加简单而存在的    因为不写这个类, 很多重复代码, 感觉恶心    真实的控件之间, 没有这种统一的共性; 不需要该类    """    def __init__(self, content):        self.content = content    def do_something(self):        print(f'print {self.__class__.__name__}({self.content})')class Container(BaseComponent):    def __init__(self, content):        self.children = []        super(Container, self).__init__(content)    def add_child(self, component: Component):        self.children.append(component)    def del_child(self, component: Component):        self.children.remove(component)    def do_something(self):        super().do_something()        for child in self.children:            child.do_something()class WinForm(Container):    """容器类: WinForm"""    # 这里也可以重写父类的方法, 实现个性化的功能class Frame(Container):    """容器组件: Frame"""class Button(BaseComponent):    """叶子组件: 按钮"""class Picture(BaseComponent):    """叶子组件: 图片"""class Label(BaseComponent):    """叶子组件: 标签"""class TextBox(BaseComponent):    """叶子组件: 文本框"""class PasswordBox(TextBox):    """叶子组件: 密码框"""class CheckBox(BaseComponent):    """叶子组件: 复选框"""class LinkLabel(Label):    """叶子组件: 复选框"""if __name__ == '__main__':    form = WinForm('WINDOW窗口')    form.add_child(Picture('LOGO图片'))    form.add_child(Button('登录'))    form.add_child(Button('注册'))    frame = Frame('FRAME1')    frame.add_child(Label('用户名'))    frame.add_child(TextBox('文本框'))    frame.add_child(Label('密码'))    frame.add_child(PasswordBox('密码框'))    frame.add_child(CheckBox('复选框'))    frame.add_child(TextBox('记住密码'))    frame.add_child(LinkLabel('忘记密码'))    form.add_child(frame)    form.do_something()
 划线
   评论
  复制
发布于: 2020 年 06 月 21 日 阅读数: 38
满山李子
  关注 
还未添加个人签名 2018.09.18 加入
还未添加个人简介
 
 
  
  
 
 
 
 
 
 
 
 
 
 
    
评论