優(yōu)雅實(shí)現(xiàn)策略模式; 在awesome-python上有一個(gè)關(guān)于模式設(shè)計(jì)的包,對(duì)包中的代碼做了一點(diǎn)修改。
# -*- coding: utf-8 -*-"""http://stackoverflow.com/questions/963965/how-is-this-strategy-pattern -written-in-python-the-sample-in-wikipediaIn most of other languages Strategy pattern is implemented via creating somebase strategy interface/abstract class and subclassing it with a number ofconcrete strategies (as we can see athttp://en.wikipedia.org/wiki/Strategy_pattern), however Python supportshigher-order functions and allows us to have only one class and injectfunctions into it's instances, as shown in this example."""import typesclass StrategyExample: def __init__(self, func=None): self.name = 'Strategy Example 0' if func is not None: self.select(func) def __call__(self, arg=''): # special method for execute self.execute() def execute(self):輸出為
nothingnothingStrategy Example 1 from execute 1Strategy Example 2 from execute 2Strategy Example 2 from execute 1Strategy Example x from execute 2
新聞熱點(diǎn)
疑難解答
網(wǎng)友關(guān)注