Python设计模式之命令模式

命令模式学习链接

#!/usr/bin/python
# coding:utf8
"""
命令行模式
"""
import abc


class Receiver(object):
	'''
	命令接收者,正在执行命令的地方,实现了众多命令函数
	'''

	def start(self):
		print('execute start command')

	def stop(self):
		print('execute stop command')

	def suspend(self):
		print('execute suspend command')

	def play(self):
		print('execute play command')


class Command(object):
	"""
	command抽象方法,子类必须要实现execute方法
	"""

	__metaclass__ = abc.ABCMeta

	@abc.abstractmethod
	def execute(self):
		pass


class Start_command(Command):
	"""
	start命令类,对命令接收者类中start方法的封装
	"""

	def __init__(self, receiver):
		self.receiver = receiver

	def execute(self):
		self.receiver.start()


class Stop_command(Command):
	"""
	stop命令类,对命令接收者类中stop方法的封装
	"""

	def __init__(self, receiver):
		self.receiver = receiver

	def execute(self):
		self.receiver.stop()


class Client(object):
	"""
	调用命令的客户端
	"""

	def __init__(self, command):
		self.command = command

	def command_do(self):
		self.command.execute()


if __name__ == '__main__':
	receiver = Receiver()
	start_command = Start_command(receiver)
	client = Client(start_command)
	client.command_do()
	# 可以直接更换命令,如下,把start命令,换成stop命令
	stop_command = Stop_command(receiver)
	client.command = stop_command
	client.command_do()

命令模式实现了分离,有助于控制命令

    原文作者:勿在浮沙筑高台LS
    原文地址: https://blog.csdn.net/baidu_15113429/article/details/85780746
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞