手机版 欢迎访问it开发者社区(www.mfbz.cn)网站

当前位置: > 开发

命令队列

时间:2021/4/20 3:33:16|来源:|点击: 次

命令队列

#!/usr/bin/env python
# -*- encoding: utf-8 -*-


class Command:
	def __init__(self):
		self.m_executedCallbackDict = {}
		self.m_undidCallbackDict = {}

	def execute(self):
		pass

	def undo(self):
		pass

	def setExecutedCallback(self, k, func):
		self.m_executedCallbackDict[k] = func

	def setUndidCallback(self, k, func):
		self.m_undidCallbackDict[k] = func

	def executedCallback(self):
		self.callback(self.m_executedCallbackDict)

	def undidCallback(self):
		self.callback(self.m_undidCallbackDict)

	def callback(self, callbackDict):
		for k, func in callbackDict.items():
			if callable(func):
				func(self)

	def getCommandUUID(self):
		return id(self)


class SequenceQueueCommand(Command):
	def __init__(self, cmds=None):
		super().__init__()
		self.m_commands = [] if cmds is None else cmds
		self.m_executingCommands = []
		self.m_executedCommands = []
		
	def appendCommand(self, cmd):
		self.m_commands.append(cmd)
	
	def insertCommand(self, index, cmd):
		self.m_commands.insert(index, cmd)
	
	def execute(self):
		if self.m_executingCommands:
			return
		if self.m_commands:
			cmd = self.m_commands.pop(0)
			cmd.setExecutedCallback(k=self.getCommandUUID(), func=self.executedOneCommand)
			self.m_executingCommands = [cmd]
			cmd.execute()
		else:
			self.executedAllCommand()

	def executedOneCommand(self, cmd):
		self.m_executedCommands.append[cmd]
		if cmd in self.m_executingCommands:
			self.m_executingCommands.remove(cmd)
		self.execute()

	def executedAllCommand(self):
		self.executedCallback()

	def undo(self):
		pass



class ParallelQueueCommand(Command):
	def __init__(self, cmds=None):
		super().__init__()
		self.m_commands = [] if cmds is None else cmds
		self.m_executingCommands = []
		self.m_executedCommands = []
	
	def execute(self):
		if self.m_executingCommands:
			return
		for cmd in self.m_commands:
			cmd.setExecutedCallback(k=self.getCommandUUID(), func=self.executedOneCommand)
			self.m_executingCommands.append(cmd)
			cmd.execute()

	def executedOneCommand(self):
		self.m_executedCommands.append[cmd]
		if cmd in self.m_executingCommands:
			self.m_executingCommands.remove(cmd)
		if not self.m_executingCommands:
			self.executedAllCommand()

	def executedAllCommand(self):
		self.executedCallback()

	def undo(self):
		pass

Copyright © 2002-2019 某某自媒体运营 版权所有