美文网首页Python精耕细作Python点滴
[Python设计模式] 08 - 外观模式

[Python设计模式] 08 - 外观模式

作者: 蓝色信仰 | 来源:发表于2015-04-03 22:21 被阅读189次

    设计模式的目的是让代码易维护、易扩展,不能为了模式而模式,因此一个简单的工具脚本是不需要用到任何模式的。

    外观模式:为子系统中的一组接口提供一个一致的界面。此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。

    基本思想

    • 一个子系统由很多功能模块组成
    • 这些功能模块分别对外暴露自己的访问接口
    • 这些功能模块联合起来对外提供该子系统的完整功能
    • 此时定义一组新的接口,将该子系统的所有模块封装起来,统一对外提供接口
    • 这个全新的接口就是原有子系统的外观

    代码结构

    class ModuleOne(object):
        def Create(self):
            print 'create module one instance'
    
        def Delete(self):
            print 'delete module one instance'
    
    class ModuleTwo(object):
        def Create(self):
            print 'create module two instance'
    
        def Delete(self):
            print 'delete module two instance'
    
    class Facade(object):
        def __init__(self):
            self.module_one = ModuleOne()
            self.module_two = ModuleTwo()
    
        def create_module_one(self):
            self.module_one.Create()
    
        def create_module_two(self):
            self.module_two.Create()
    
        def create_both(self):
            self.module_one.Create()
            self.module_two.Create()
    
        def delete_module_one(self):
            self.module_one.Delete()
    
        def delete_module_two(self):
            self.module_two.Delete()
    
        def delete_both(self):
            self.module_one.Delete()
            self.module_two.Delete()
    

    有点类似代理模式,不同之处是,外观模式不仅代理了一个子系统的各个模块的功能,同时站在子系统的角度,通过组合子系统各模块的功能,对外提供更加高层的接口,从而在语义上更加满足子系统层面的需求。

    随着系统功能的不断扩张,当需要将系统划分成多个子系统或子模块,以减少耦合、降低系统代码复杂度、提高可维护性时,代理模式通常会有用武之地。

    原文地址:http://www.isware.cn/python-design-pattern/08-facade/

    相关文章

      网友评论

        本文标题:[Python设计模式] 08 - 外观模式

        本文链接:https://www.haomeiwen.com/subject/fghaxttx.html