Python 设计模式 (一)

Python 设计模式 (一)

01 工厂模式

https://blog.csdn.net/sunt2018/article/details/84786264

https://blog.csdn.net/sunt2018/article/details/84786476

02 建造者模式

https://blog.csdn.net/sunt2018/article/details/84786624

03 原型模式

原型模式的目的是克隆对象 或者 副本

类似于浅拷贝和深拷贝

浅拷贝就是 副本依赖引用
深拷贝就是 完全克隆一份

https://blog.csdn.net/sunt2018/article/details/84789114

04 适配器模式

将一个类的接口转换成为客户希望的另外一个接口

使得原本由于接口不兼容而不能一起工作的那些类可以一起工作

class Target(object):
    def request(self):
        print("普通请求") 

class Adaptee(object):
    def specific_request(self):
        print("特殊请求")

class Adapter(Target):

    def __init__(self):
        self.adaptee = Adaptee()

    def request(self):
        self.adaptee.specific_request()


if __name__ == "__main__":
    target = Adapter()
    target.request()
    
#-------------------------------
# Target 已有的类 
target = Target()
target.request()

# 当其他调用者不兼容的时候,我们可以给他一个兼容的类
target = Adapter()
target.request()

05 装饰器模式

学习Python的装饰器

https://blog.csdn.net/sunt2018/article/details/85989249

装饰器设计模式

https://blog.csdn.net/ZhangQiye1993/article/details/82348283

06 外观模式

外观模式包含如下角色: Facade: 外观角色 SubSystem:子系统角色

假设有一组火警报警系统,由三个子元件构成:一个警报器,一个喷水器,一个自动拨打电话的装置。

class AlarmSensor:
    # 报警传感器
    def run(self):
        print("Alarm Ring...")
class WaterSprinker:
    # 喷水器
    def run(self):
        print("Spray Water...")
class EmergencyDialer: 
    #紧急拨打电话装置
    def run(self):
        print("Dial 119...")

class EmergencyFacade:
    """
    外观类中封装了对子系统的操作
    """
    def __init__(self):
        self.alarm_sensor=AlarmSensor()
        self.water_sprinker=WaterSprinker()
        self.emergency_dialer=EmergencyDialer()
    def runAll(self):
        self.alarm_sensor.run()
        self.water_sprinker.run()
        self.emergency_dialer.run()

if __name__=="__main__":
    emergency_facade=EmergencyFacade()
    emergency_facade.runAll()

07 享元模式

享元模式是一种用于解决资源和性能压力时会使用到的设计模式

它的核心思想是通过引入数据共享来提升性能

单例模式实现的是一个类对象只允许有一个实例对象

而享元模式则是一个类对象只允许创建不同类型的对象

import random
from enum import Enum

TreeType = Enum('TreeType', 'apple_tree cherry_tree peach_tree')

class Tree:
    pool = dict()
    def __new__(cls, tree_type):
        obj = cls.pool.get(tree_type, None)
        if not obj:
            obj = object.__new__(cls)
            cls.pool[tree_type] = obj
            obj.tree_type = tree_type
        return obj

    def render(self, age, x, y):
        print('render a tree of type {} and age {} at ({}, {})'.format(
            self.tree_type, age, x, y))


def main():
    rnd = random.Random()
    age_min, age_max = 1, 30 # 单位为年
    min_point, max_point = 0, 100
    tree_counter = 0

    # apple_tree
    for _ in range(10):
        t1 = Tree(TreeType.apple_tree) 
        t1.render(rnd.randint(age_min, age_max),
                rnd.randint(min_point, max_point),
                rnd.randint(min_point, max_point))
        tree_counter += 1

    # cherry_tree
    for _ in range(3):
        t2 = Tree(TreeType.cherry_tree)
        t2.render(rnd.randint(age_min, age_max),
                rnd.randint(min_point, max_point),
                rnd.randint(min_point, max_point))
        tree_counter += 1

    # peach_tree
    for _ in range(5):
        t3 = Tree(TreeType.peach_tree)
        t3.render(rnd.randint(age_min, age_max),
                    rnd.randint(min_point, max_point),
                    rnd.randint(min_point, max_point))
        tree_counter += 1

    
    print('trees rendered: {}'.format(tree_counter))               # 一共循环了18次
    print('trees actually created: {}'.format(len(Tree.pool)))     # 3次 因为只有3个不重复
    t4 = Tree(TreeType.cherry_tree)
    t5 = Tree(TreeType.cherry_tree)
    t6 = Tree(TreeType.apple_tree)
    print('{} == {}? {}'.format(id(t4), id(t5), id(t4) == id(t5))) # True
    print('{} == {}? {}'.format(id(t5), id(t6), id(t5) == id(t6))) # False

main()

08 模型-视图-控制器模式

这就我们常说的MVC模式


class View(object):
    # 视图
    def __init__(self, controller):
        self.controller = controller
 
    def show(self):
        self.controller.show()
 
    def add(self, key, value):
 
        self.controller.add(key, value)
 
    def remove(self, key):
        self.controller.remove(key)
 
 
class Controller(object):
    # 控制器
    def __init__(self, model):
        self.model = model
 
    def show(self):
        for key, item in self.model.items():
            print(key, item)
 
    def add(self, key, value):
        self.model[key] = value
 
    def remove(self,key):
        if key in self.model.keys():
            self.model.pop(key)
 
 
class Model(dict):
    # 模型
    pass
 
 
if __name__ == '__main__':
    # model 其实就是一个列表
    model = Model(
    	[(0,'xiaoming'),(1,'xiaohua'),
    	(2, 'xiaogang'),(3,'xiaohua'),(4,'xiaoli')
    	])
    
    controller = Controller(model)
    view = View(controller)
    view.show()
    print('*'*100)
    view.add(5,'laoliu')
    view.show()
    print('*'*100)
    view.remove(0)
    view.show()
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 撸撸猫 设计师:C马雯娟 返回首页