设计模式

常见的设计模式

中文译名:设计模式 - 可复用的面向对象软件元素 中所提到的,总共有 23 种设计模式。这些模式可以分为三大类:

创建型模式(Creational Patterns)

结构型模式(Structural Patterns)

行为型模式(Behavioral Patterns)

外加,J2EE 设计模式。

创建型模式

单例模式

import threading


config_dict = {}


class Config:
    def __new__(cls, *args, **kwargs):
        if not hasattr(Config, "_instance"):
            with threading.Lock():
                if not hasattr(Config, "_instance"):
                    print("-----create instance-------")
                    Config._instance = super().__new__(cls, *args, **kwargs)
        return Config._instance

    def __init__(self):
        self.load_config()


    def load_config(self):
        config_dict.update({"data_path": "ssss"})


def get_config(param):
    if not config_dict:
        Config()
    return config_dict[param]


b = Config()
c = Config()

print(b)
print(c)

原型模式

# 当某个类,初始化操作复杂时,使用

import copy
class Book:
    def __init__(self, book_name=None, author=None):
        self.book_name = book_name
        self.author = author


class ProtoType:
    def __init__(self):
        self.objects = {}

    def register(self, obj_id, obj):
        self.objects[obj_id] = obj

    def clone(self, origin_id, **kwargs):
        if not self.objects.get(origin_id):
            raise Exception("Origin_id not exist!")

        origin_obj = self.objects.get(origin_id)
        new_obj = copy.deepcopy(origin_obj)
        new_obj.__dict__.update(kwargs)
        return new_obj


b_obj1 = Book(book_name="book1", author="author1")

p = ProtoType()
p.register("bbb111", b_obj1)
b_obj2 = p.clone("bbb111")

print(b_obj1 is b_obj2)

工厂模式

结构型模式

装饰器模式

from collections import defaultdict
import time
import datetime


def cal_time(limit):
    def _cal_time(f):
        def wrapper(*args, **kwargs):
            start = time.time()
            f_ret = f(*args, **kwargs)
            total = time.time() - start
            query = args[0].get("query")
            if total > limit:
                print("函数运行时间:{}  查询的query为:{}".format(total, query))
            return f_ret
        return wrapper
    return _cal_time


def metrics(f):
    def wrapper(*args, **kwargs):
        f_ret = f(*args, **kwargs)
        metric_dict = defaultdict(int)
        for data in f_ret:
            for k, v in data.items():
                if k == "type":
                    metric_dict[v] += 1

        print("metric_dict:", metric_dict)

        return f_ret

    return wrapper


@cal_time(0.5)
@metrics
def f(request_dict):
    time.sleep(0.5)
    return [{"type": "song", "value": 1}, {"type": "song", "value": 2}, {"type": "album", "value": 1}, {"type": "artist", "value": 1}]


f({"query": "a"})

MVC模式

view  >> business  >> handler

行为型模式

观察者模式

# 一对多关系,发布订阅模式
class Sender:
    def __init__(self):
        self.receivers = []

    def send_msg(self, msg):
        for receiver in self.receivers:
            receiver.receive(msg)

    def add_receiver(self, receiver):
        self.receivers.append(receiver)


class Receive:
    def __init__(self, receiver_id):
        self.receiver_id = receiver_id

    def receive(self, msg):
        print("当前的接受者为:{},接受的消息为:{}".format(self.receiver_id, msg))


s = Sender()
r1 = Receive("1")
r2 = Receive("2")
s.add_receiver(r1)
s.add_receiver(r2)

s.send_msg("第一次")

你可能感兴趣的:(设计模式)