Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
PyCon2013China_ZhuHai_laiyonghao
Search
Sponsored
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
Zoom.Quiet
December 08, 2013
Technology
1.2k
2
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
PyCon2013China_ZhuHai_laiyonghao
PyCon2013China 珠海场 | GDG Livin ZhuHai Life;-)
http://zhgdg.gitcafe.com/2013-12/et-pycon/
Zoom.Quiet
December 08, 2013
More Decks by Zoom.Quiet
See All by Zoom.Quiet
PyCon2014China-Zhuhai-high performance
zoomquiet
0
220
PyCon2014China-Zhuhai-meta programming
zoomquiet
1
190
PyCon2014China-Zhuhai-bpm.py
zoomquiet
0
160
PyCon2014China-Zhuhai-luna kv db
zoomquiet
0
170
PyCon2014China-Zhuhai-seed studio
zoomquiet
0
170
PyCon2014China-Zhuhai-Docker Registry Build By Python
zoomquiet
0
180
PyCon2014China-Zhuhai-jeff
zoomquiet
0
160
PyCon2014China-Zhuhai-pythonic front-end
zoomquiet
0
220
DevFest2014-Zhuhai-Polymer
zoomquiet
0
500
Other Decks in Technology
See All in Technology
AI Agent 時代のデータ基盤: ClickHouse で実現する 超高速分析とコスト削減の両立
jozono
0
200
[JAWS Festa 2026]一番いい仕事は、請求書に現れない / jawsfesta2026
sh_fk2
2
220
Content Mapper APIの応用例~CSS Modules、言語ファイル~
uhyo
2
620
公共分野での生成AI活用
toru_kubota
1
250
In-Context Learning再入門。ICLの勾配降下的解釈の研究動向を追ってみる。
dai08srhg
1
580
Gifu WordPress Meetup #200 に向けて、私たちには何ができるだろうか?/ 2026-11-07 Gifu WordPress Meetup
torounit
0
190
cdkd (CDK Direct)
gotok365
4
250
Metadata - Section 3 : Dublin Core Standard · DC
mohab1
0
110
Maestro MCPとClaude Code Skillsによる自律的なE2Eテスト支援
asmz
0
420
DBTS2026 盛り上がってますか!?Databricksが実現するAI時代のデータ基盤
akuwano
1
190
Context Ontology Accelerator 入門 (業務データの意味を、AI エージェントに渡す)
inariku
PRO
3
430
AIエージェントの監視、思考を見るか行動を見るか / Monitoring AI Agents: Thoughts or Actions
yusukeshimizu
2
170
Featured
See All Featured
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
46
3.1k
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
35
2.6k
Building Adaptive Systems
keathley
44
3.3k
Marketing Yourself as an Engineer | Alaka | Gurzu
gurzu
0
360
Build your cross-platform service in a week with App Engine
jlugia
234
19k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
35
3.9k
From π to Pie charts
rasagy
1
440
Visual Storytelling: How to be a Superhuman Communicator
reverentgeek
2
740
Organizational Design Perspectives: An Ontology of Organizational Design Elements
kimpetersen
PRO
1
880
The Hidden Cost of Media on the Web [PixelPalooza 2025]
tammyeverts
2
570
The Cost Of JavaScript in 2023
addyosmani
56
10k
HTML-Aware ERB: The Path to Reactive Rendering @ RubyCon 2026, Rimini, Italy
marcoroth
5
900
Transcript
+ 论 Python 与设计模式 赖勇浩(http://laiyonghao.com) 2013-‐12-‐8
珠海
+ 设计模式?
+ 自我介绍 n 赖勇浩 n 从业 8
年多,主要编程语言是 Python n game -‐> webgame -‐> web n 常在珠三角技术沙龙出没 n http://laiyonghao.com 3
+ PyCon 的老朋友 4
+ 好,正式开始吧! 5
+ 先热热场子…… n 写 Python 代码赚钱的,有没有? 6
+ 先热热场子…… n 写 Python 代码赚钱的,有没有? n
写 Python 超过 1 年的,有没有? 7
+ 再热热场子…… n 读过《设计模式——可复用面向对 象软件的基础》这本书的有没有? 8
+ 再热热场子…… n 读过《设计模式——可复用面向对 象软件的基础》这本书的有没有? n 读过《Head
First 设计模式》 的有没有? 9
10 一个观点
+ 我也希望是这样…… 但事实是…… 11
+ 先看事实:工厂函数(方法) int(…) float(…) type(name, bases,
dict) >>> class X(object): ... a = 1 ... >>> X = type('X', (object,), dict(a=1)) collections.namedtuple() datatime.fromtimestamp(…) Decimal.from_float(…) Fraction.from_float(…) Fraction.from_decimal(…)
+ 先看事实:享元(FlyWeight) >>> i = 10 >>>
j = 5 + 5 >>> id(i) 140479275503872 >>> id(j) 140479275503872 >>> a = 'ab' >>> b = 'a' + 'b' >>> id(a) == id(b) True 13
+ 先看事实:享元(FlyWeight) >>> i = 10 >>>
j = 5 + 5 >>> id(i) 140479275503872 >>> id(j) 140479275503872 >>> a = 'ab' >>> b = 'a' + 'b' >>> id(a) == id(b) True >>> a = a * 10 >>> intern(a) 'abababababababababab' >>> b = 'abababababababababab’ >>> c = 'abababababababababa' + 'b’ >>> d = 'ab' * 10 >>> id(a) == id(b) == id(c) == id(d) True 14
+ 先看事实:适配器 import SocketServer class ThreadedTCPServer(SocketServer.ThreadingMixIn,
SocketServer.TCPServer): pass 15
+ 先看事实:代理模式 >>> import weakref >>> class
A(object):pass ... >>> a = A() >>> a.attr = 1 >>> a.attr 1 >>> a1 = weakref.proxy(a) >>> a1.attr 1 >>> a1 <weakproxy at 0x10dc375d0 to A at 0x10dc3a410> 16
+ 先看事实:模板方法 import SocketServer class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self): self.data = self.request.recv(1024).strip() print "{} wrote:".format(self.client_address[0]) print self.data self.request.sendall(self.data.upper()) 17
+ 先看事实:模板方法 From abc import ABCMeta class
C: __metaclass__ = ABCMeta @abstractmethod def my_abstract_method(self, ...): ... 18
+ 所以,真相是…… n 标准库都在用…… n 标准库都推荐用…… n 怎么可以说不需要?!
19
+ 所以我们不是不需要模式…… 而是要 Pythonic 的模式实现…… 20
+ 不 Pythonic 的设计模式:单例 class Singleton(object):
def __new__(cls, *args, **kw): if not hasattr(cls, '_instance'): orig = super(Singleton, cls) cls._instance = orig.__new__(cls, *args, **kw) return cls._instance 21
+ 单例的三个需求: n 只能有一个实例; n 它必须自行创建这个实例;
n 它必须自行向整个系统提供这个 实例。 22
+ 单例遇上并行 class Singleton(object):
objs = {} objs_locker = threading.Lock() def __new__(cls, *args, **kv): if cls in cls.objs: return cls.objs[cls] 23
+ 单例遇上并行
cls.objs_locker.acquire() try: if cls in cls.objs: return cls.objs[cls] cls.objs[cls] = object.__new__(cls) finally: cls.objs_locker.release() 24
+ Pythonic 的设计模式:单例 n 重新审视 Python 的语法元素,尽量利用已有基础设施。
n 模块 n 所有的变量都会绑定到模块; n 模块只初始化一次; n import 机制是线程安全的(保证了在并发状态下模块也只有一个实 例); n 惯用法: n 文件名首字母大写,如 Moon.py n __all__ 25
+ 不 Pythonic 的设计模式:装饰器 26
+ 代码大概是这样的 class darkroast(Beverage): def cost(self):return
0.99 … class Whip(Beverage): def __init__(self, beverage): self._beverage = beverage def cost(self): return self._beverage.cost() + 0.1 print Whip(Mocha(darkroast())).cost() 27
+ Pythonic 的设计模式:装饰器 def beverage(cost): def
_(orig = 0.0): return orig + cost return _ darkroast = beverage(0.99) whip = beverage(0.1) mocha = beverage(0.2) print whip(mocha(darkroast())) 28
+ 其它设计模式:Borg(MonoState) n 保持对象的唯一性并不重要,只 要共享状态就行 n Alex
Martelli n http:// code.activestate.com/ recipes/66531/ 29
+ 其它设计模式:Borg(MonoState) class Borg(object):
_state = {} def __new__(cls, *args, **kw): ob = super(Borg, cls).__new__(cls, *args, **kw) ob.__dict__ = cls._state return ob 30
+ 动态语言特有的设计模式:mixin n 动态地改变实例的类型的基类,在不修改生成实例过程的情况下, 给实例增加(改变)功能。可用以实现插件框架。 class Bird(object):pass
bird = Bird() class FlyMixin: def fly(self):print 'I can fly.' bird.__class__.__bases__ += (FlyMixin, ) bird.fly() 31
+ 动态语言特有的模式:duck typing n 一个对象有效的语义,不是由继承自特定的类或实现特定的接口, 而是由当前方法和属性的集合决定。 n
当看到一只鸟走起来像鸭子、游泳起来像鸭子、叫起来也像鸭子, 那么这只鸟就可以被称为鸭子。(James Whitcomb Riley) n 干掉模板方法? n 不,模板方法是想要保证子类实现接口 32
+ 利用设计模式提供更好的接口 n getopt n optparse
n argparse n docopt n Command-‐line interface description language n define interface for your command-‐line app, and n automatically generate parser for it. n 解释器模式 33
+ docopt 34
+ 解释器模式的应用 n GM 指令 player 0
money 10000 player 0 attack 10000 monster 0 die scene monsters die n 过场剧情脚本 monster 0 spawn 0,0 monster 0 moveto 0,-‐10 monster 0 attack monster 0 moveto 0,0 35
+ Q&A
[email protected]
36