[python]设计模式

Posted 李雷雷

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[python]设计模式相关的知识,希望对你有一定的参考价值。

1.单例模式

#-*- encoding=utf-8 -*-

class Singleton(object):
    def __new__(cls, *args, **kw):
        if not hasattr(cls, _instance):
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)
        return cls._instance

a = Singleton()
b = Singleton()
print id(a)
print id(b)

 

2.模板模式

#coding:utf-8

class CaffeineBeverageWithHook(object):
    def prepareRecipe(self):
        self.boilWater()
        self.brew()
        self.pourInCup()
        if self.customerWantsCondiments():
            self.addCondiments()

    def brew(self):
        print "start brew."

    def addCondiments(self):
        pass

    def boilWater(self):
        print "start boilWater."

    def pourInCup(self):
        print "Pour into cup"

    def customerWantsCondiments(self):
        return False

class CoffeeWithHook(CaffeineBeverageWithHook):
    def brew(self):
        print "Dripping coffee through filter."

    def addCondiments(self):
        print "Add Sugar and Milk."

    def customerWantsCondiments(self):
        return True

if __name__ == __main__:
    coffeeWithHook = CoffeeWithHook()
    coffeeWithHook.prepareRecipe()

 

3.适配器模式

#coding: utf-8

class Target(object):
    def request(self):
        print "this is target.request method."

class Adaptee(object):
    def special_request(self):
        print "this is Adaptee.special_request method."

class Adapter(object):
    def __init__(self):
        self.special_req = Adaptee()

    def request(self):
        self.special_req.special_request()


if __name__ == __main__:
    adapter = Adapter()
    adapter.request()

 

以上是关于[python]设计模式的主要内容,如果未能解决你的问题,请参考以下文章

python 有用的Python代码片段

Python 向 Postman 请求代码片段

python [代码片段]一些有趣的代码#sort

使用 Python 代码片段编写 LaTeX 文档

python 机器学习有用的代码片段

python 代码片段和解决方案