详解Python设计模式编程中观察者模式与策略模式的运用
观察者模式
观察者模式:又叫发布订阅模式,定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象,这个主题对象的状态发生变化时,会通知所有观察者对象,是他们能自动更新自己。
代码结构
class Topic(object): """主题类。保存所有观察者实例的引用,每个主题都可以有很多观察者 可以增加和删除观察者""" def __init__(self): self.obs = [] def Attach(self, ob): self.obs.append(ob) def Detach(self, ob): self.obs.remove(ob) def Notify(self): for ob in self.obs: ob.Update() class Observer(object): """抽象观察者类,收到主题的变更通知时,更新自己""" def Update(self): raise NotImplementedError() class ConcreteTopic(object): """一个具体主题""" def __init__(self): self.state = None def ChangeState(self, newState): self.state = newState self.Notify() class ConcreteObserver(object): """一个具体监听类""" def __init__(self, topic): self.topic = topic def Update(self): print self.topic.state def client(): topic = ConcreteTopic() topic.Attach(ConcreteObserver(topic)) topic.ChangeState('New State')
众多MQ中间件都是采用这种模式的思想来实现的。
观察者模式可以让主题和观察者之间解耦,互相之间尽可能少的依赖。不过抽象主题和抽象观察者之间还是有耦合的。
策略模式
策略模式: 定义了算法家族,分别封装起来,让他们之间可以互相替换。此模式让算法的变化不影响使用算法的客户。
代码框架
class Strategy(object): """抽象算法类""" def AlgorithmInterface(self): raise NotImplementedError() class ConcreteStrategyA(Strategy): def AlgorithmInterface(self): print '算法A' class ConcreteStrategyB(Strategy): def AlgorithmInterface(self): print '算法B' class Context(object): """上下文,作用就是封装策略的实现细节,用户只需要知道有哪些策略可用""" def __init__(self, strategy): # 初始化时传入具体的策略实例 self.strategy = strategy def ContextInterface(self): # 负责调用具体的策略实例的接口 self.strategy.AlgorithmInterface() def client(cond): # 策略模式的使用演示 # 用户只需要根据不同的条件,将具体的算法实现类传递给Context, # 然后调用Context暴露给用户的接口就行了。 if cond == 'A': context = Context(ConcreteStrategyA()) elif cond == 'B': context = Context(ConcreteStrategyB()) result = context.ContextInterface()
策略模式解决那类问题
在回答这个问题之前,先说下对策略模式的使用方式的感觉。上面的client函数,怎么看起来就像是简单工厂模式中的工厂函数呢?确实如此,实际上策略模式可以和简工厂模式结合起来,将更多细节封装在策略模式内部,让使用者更容易的使用。
那么策略模式和简单工厂模式有什么不同呢?策略模式中的算法是用来解决同一个问题的,根据时间、条件不同,算法的具体细节有差异,但最终解决的是同一个问题。在需求分析过程中,当听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式来处理这种变化的可能性。
缺点
使用者需要知道每一种策略的具体含义,并负责选择策略
改进
结合简单工厂模式,将策略选择封装在Context内部,解放client:
class Context(object): def __init__(self, cond): if cond == 'A': self.strategy = Context(ConcreteStrategyA()) elif cond == 'B': self.strategy = Context(ConcreteStrategyB()) def ContextInterface(self): self.strategy.AlgorithmInterface() def client(cond): context = Context(cond) result = context.ContextInterface()
改进后的遗留问题
每次需要增加新的策略时,就需要修改Context的构造函数,增加一个新的判断分支。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.
