def
用一个中介对象封装一系列的对象交互, 中介者使各对象不需要显示地相互作用, 从而使其耦合松散, 而且可以独立地改变它们之间的交互。
usage
中介者模式的优点就是减少类间的依赖, 把原有的一对多的依赖变成了一对一的依赖,同事类只依赖中介者, 减少了依赖, 当然同时也降低了类间的耦合。
中介者模式的缺点就是中介者会膨胀得很大, 而且逻辑复杂, 原本N个对象直接的相互依赖关系转换为中介者和同事类的依赖关系, 同事类越多, 中介者的逻辑就越复杂。
中介者模式是一个非常好的封装模式, 也是一个很容易被滥用的模式, 一个对象依赖几个对象是再正常不过的事情, 但是纯理论家就会要求使用中介者模式来封装这种依赖关系,这是非常危险的! 使用中介模式就必然会带来中介者的膨胀问题, 这在一个项目中是很不恰当的。 大家可以在如下的情况下尝试使用中介者模式:
● N个对象之间产生了相互的依赖关系(N>2) 。
● 多个对象有依赖关系, 但是依赖的行为尚不确定或者有发生改变的可能, 在这种情况下一般建议采用中介者模式, 降低变更引起的风险扩散。
● 产品开发。 一个明显的例子就是MVC框架, 把中介者模式应用到产品中, 可以提升产品的性能和扩展性, 但是对于项目开发就未必, 因为项目是以交付投产为目标, 而产品则是以稳定、 高效、 扩展为宗旨。
code
class TC:
def __init__(self):
self._tm = None
self._bProblem = 0
def setup(self):
print("Setting up the Test")
time.sleep(0.1)
self._tm.prepareReporting()
def execute(self):
if not self._bProblem:
print("Executing the test")
time.sleep(0.1)
else:
print("Problem in setup. Test not executed.")
def tearDown(self):
if not self._bProblem:
print("Tearing down")
time.sleep(0.1)
self._tm.publishReport()
else:
print("Test not executed. No tear down required.")
def setTM(self, tm):
self._tm = tm
def setProblem(self, value):
self._bProblem = value
class Reporter:
def __init__(self):
self._tm = None
def prepare(self):
print("Reporter Class is preparing to report the results")
time.sleep(0.1)
def report(self):
print("Reporting the results of Test")
time.sleep(0.1)
def setTM(self, tm):
self._tm = tm
class DB:
def __init__(self):
self._tm = None
def insert(self):
print("Inserting the execution begin status in the Database")
time.sleep(0.1)
# Following code is to simulate a communication from DB to TC
if random.randrange(1, 4) == 3:
return -1
def update(self):
print("Updating the test results in Database")
time.sleep(0.1)
def setTM(self, tm):
self._tm = tm
class TestManager:
def __init__(self):
self._reporter = None
self._db = None
self._tc = None
def prepareReporting(self):
rvalue = self._db.insert()
if rvalue == -1:
self._tc.setProblem(1)
self._reporter.prepare()
def setReporter(self, reporter):
self._reporter = reporter
def setDB(self, db):
self._db = db
def publishReport(self):
self._db.update()
self._reporter.report()
def setTC(self, tc):
self._tc = tc
if __name__ == '__main__':
reporter = Reporter()
db = DB()
tm = TestManager()
tm.setReporter(reporter)
tm.setDB(db)
reporter.setTM(tm)
db.setTM(tm)
# For simplification we are looping on the same test.
# Practically, it could be about various unique test classes and their
# objects
for i in range(3):
tc = TC()
tc.setTM(tm)
tm.setTC(tc)
tc.setup()
tc.execute()
tc.tearDown()