码迷,mamicode.com
首页 > 编程语言 > 详细

[python]设计模式

时间:2016-06-30 01:07:47      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

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]设计模式

标签:

原文地址:http://www.cnblogs.com/alexkn/p/5628612.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!