" name="sm-site-verification"/>
侧边栏壁纸
博主头像
PySuper 博主等级

千里之行,始于足下

  • 累计撰写 206 篇文章
  • 累计创建 14 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

23种设计模式及Python实现 -- 结构型

PySuper
2019-10-21 / 0 评论 / 0 点赞 / 7 阅读 / 0 字
温馨提示:
本文最后更新于2024-05-28,若内容或图片失效,请留言反馈。 所有牛逼的人都有一段苦逼的岁月。 但是你只要像SB一样去坚持,终将牛逼!!! ✊✊✊

适配器

将一个类的接口转换成客户希望的另外一个接口。Adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作

  • 你想使用一个已经存在的类,而它的接口不符合你的需求
  • 你想创建一个可以复用的类,该类可以与其他不相关的类或不可预见的类协同工作
  • 你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口==>对象适配器可以适配它的父类接口
import os

class Dog(object):

    def __init__(self):
        self.name = "Dog"

    def bark(self):
        return "woof!"

class Cat(object):

    def __init__(self):
        self.name = "Cat"

    def meow(self):
        return "meow!"

class Human(object):

    def __init__(self):
        self.name = "Human"

    def speak(self):
        return "'hello'"

class Car(object):

    def __init__(self):
        self.name = "Car"

    def make_noise(self, octane_level):
        return "vroom%s" % ("!" * octane_level)


class Adapter(object):

    def __init__(self, obj, adapted_methods):
        self.obj = obj
        self.__dict__.update(adapted_methods)

    def __getattr__(self, attr):
        return getattr(self.obj, attr)

def main():
    objects = []
    dog = Dog()
    objects.append(Adapter(dog, dict(make_noise=dog.bark)))
    cat = Cat()
    objects.append(Adapter(cat, dict(make_noise=cat.meow)))
    human = Human()
    objects.append(Adapter(human, dict(make_noise=human.speak)))
    car = Car()
    car_noise = lambda: car.make_noise(3)
    objects.append(Adapter(car, dict(make_noise=car_noise)))
    for obj in objects:
        print "A", obj.name, "goes", obj.make_noise()

if __name__ == "__main__":
    main()

桥接

将抽象部分与它的实现部分分离,使它们都可以独立地变化

  • 你不希望在抽象和它的实现部分之间有一个固定的绑定关系
  • 类的抽象以及它的实现都应该可以通过生成子类的方法加以扩充
  • 对一个抽象的实现部分的修改应对客户不产生影响,即客户的代码不必重新编译
  • 有许多类要生成
  • 你想在多个对象间共享实现(可能使用引用计数),但同时要求客户并不知道这一点
class DrawingAPI1(object):
    def draw_circle(self, x, y, radius):
        print('API1.circle at {}:{} radius {}'.format(x, y, radius))

class DrawingAPI2(object):

    def draw_circle(self, x, y, radius):
        print('API2.circle at {}:{} radius {}'.format(x, y, radius))

class CircleShape(object):

    def __init__(self, x, y, radius, drawing_api):
        self._x = x
        self._y = y
        self._radius = radius
        self._drawing_api = drawing_api

    def draw(self):
        self._drawing_api.draw_circle(self._x, self._y, self._radius)

    def scale(self, pct):
        self._radius *= pct

def main():
    shapes = (
        CircleShape(1, 2, 3, DrawingAPI1()),
        CircleShape(5, 7, 11, DrawingAPI2())
    )

    for shape in shapes:
        shape.scale(2.5)
        shape.draw()


if __name__ == '__main__':
    main()

组合

将对象组合成树形结构以表示“部分-整体”的层次结构。C o m p o s i t e 使得用户对单个对象和组合对象的使用具有一致性

  • 你想表示对象的部分-整体层次结构
  • 你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象
class Component:

    def __init__(self,strName):
        self.m_strName = strName

    def Add(self,com):
        pass

    def Display(self,nDepth):
        pass

class Leaf(Component):

    def Add(self,com):
        print "leaf can't add"

    def Display(self,nDepth):
        strtemp = "-" * nDepth
        strtemp=strtemp+self.m_strName
        print strtemp


class Composite(Component):

    def __init__(self,strName):
        self.m_strName = strName
        self.c = []

    def Add(self,com):
        self.c.append(com)

    def Display(self,nDepth):
        strtemp = "-"*nDepth
        strtemp=strtemp+self.m_strName
        print strtemp
        for com in self.c:
            com.Display(nDepth+2)

if __name__ == "__main__":
    p = Composite("Wong")
    p.Add(Leaf("Lee"))
    p.Add(Leaf("Zhao"))
    p1 = Composite("Wu")
    p1.Add(Leaf("San"))
    p.Add(p1)
    p.Display(1)

装饰

动态地给一个对象添加一些额外的职责。就增加功能来说,相比生成子类更为灵活

  • 在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责
  • 处理那些可以撤消的职责
  • 当不能采用生成子类的方法进行扩充时
class foo(object):

    def f1(self):
        print("original f1")

    def f2(self):
        print("original f2")


class foo_decorator(object):

    def __init__(self, decoratee):
        self._decoratee = decoratee

    def f1(self):
        print("decorated f1")
        self._decoratee.f1()

    def __getattr__(self, name):
        return getattr(self._decoratee, name)

u = foo()
v = foo_decorator(u)
v.f1()
v.f2()

外观

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

  • 当你要为一个复杂子系统提供一个简单接口时
  • 客户程序与抽象类的实现部分之间存在着很大的依赖性
  • 当你需要构建一个层次结构的子系统时,使用外观模式定义子系统中每层的入口点
import time


SLEEP = 0.5

class TC1:
    def run(self):
        print("###### In Test 1 ######")
        time.sleep(SLEEP)
        print("Setting up")
        time.sleep(SLEEP)
        print("Running test")
        time.sleep(SLEEP)
        print("Tearing down")
        time.sleep(SLEEP)
        print("Test Finished\n")

class TC2:
    def run(self):
        print("###### In Test 2 ######")
        time.sleep(SLEEP)
        print("Setting up")
        time.sleep(SLEEP)
        print("Running test")
        time.sleep(SLEEP)
        print("Tearing down")
        time.sleep(SLEEP)
        print("Test Finished\n")

class TC3:

    def run(self):
        print("###### In Test 3 ######")
        time.sleep(SLEEP)
        print("Setting up")
        time.sleep(SLEEP)
        print("Running test")
        time.sleep(SLEEP)
        print("Tearing down")
        time.sleep(SLEEP)
        print("Test Finished\n")

class TestRunner:

    def __init__(self):
        self.tc1 = TC1()
        self.tc2 = TC2()
        self.tc3 = TC3()
        self.tests = [i for i in (self.tc1, self.tc2, self.tc3)]

    def runAll(self):
        [i.run() for i in self.tests]

if __name__ == '__main__':
    testrunner = TestRunner()
    testrunner.runAll()

享元

运用共享技术有效地支持大量细粒度的对象

  • 一个应用程序使用了大量的对象
  • 完全由于使用大量的对象,造成很大的存储开销
  • 对象的大多数状态都可变为外部状态
  • 如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象
  • 应用程序不依赖于对象标识
import weakref 


class Card(object):

    _CardPool = weakref.WeakValueDictionary()

    def __new__(cls, value, suit):        
        obj = Card._CardPool.get(value + suit, None)        
        if not obj:            
            obj = object.__new__(cls)            
            Card._CardPool[value + suit] = obj            
            obj.value, obj.suit = value, suit         
        return obj

    def __repr__(self):        
        return "" % (self.value, self.suit)     

if __name__ == '__main__':
    c1 = Card('9', 'h')
    c2 = Card('9', 'h')
    print(c1, c2)
    print(c1 == c2)
    print(id(c1), id(c2))

代理

为其他对象提供一种代理以控制对这个对象的访问

  • 在需要用比较通用和复杂的对象指针代替简单的指针的时候,使用代理模式
    • 远程代理:为一个对象在不同的地址空间提供局部代表
    • 虚代理:根据需要创建开销很大的对象
    • 保护代理控制对原始对象的访问
    • 智能指引取代了简单的指针,它在访问对象时执行一些附加操作
import time


class SalesManager:

    def work(self):
        print("Sales Manager working...")

    def talk(self):
        print("Sales Manager ready to talk")


class Proxy:

    def __init__(self):
        self.busy = 'No'
        self.sales = None

    def work(self):
        print("Proxy checking for Sales Manager availability")
        if self.busy == 'No':
            self.sales = SalesManager()
            time.sleep(2)
            self.sales.talk()
        else:
            time.sleep(2)
            print("Sales Manager is busy")


if __name__ == '__main__':
    p = Proxy()
    p.work()
    p.busy = 'Yes'
    p.work()
0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区