# -*- coding: utf-8 -*- __author__ = 'cty' __date__ = '2019/5/13 21:28' # 大数据集群业务需求中有一个Log类原本只有“离线收集日志”, # 现在新增需求希望给日志做实时大数据分析 # 原有实现 class Log(object): def __init__(self): pass def LogOfflineCollection(self, log_dir): print("Collecting the log files under {}. offline.".format(log_dir)) def LogOnlineAnalysis(self, log_dir): print("Analyzing the log files under {}. online.".format(log_dir)) class Client(object): def __init__(self): pass def act(self): log = Log() log.LogOfflineCollection("C:\\cty\\logs\\") log.LogOfflineCollection("/opt/logs") log.LogOnlineAnalysis("C:\\cty\\logs\\") log.LogOnlineAnalysis("/opt/logs") # if __name__ == '__main__': # client = Client() # client.act() # 单一职责原则(Single Responsibility Principle):一个类负责一项职责,单纯的快乐 # 优化代码 # 职责拆分后的实现 class LogOfflineCollection(object): def __init__(self): pass def collect(self, log_dir): print("Collecting the log files under {}. offline.".format(log_dir)) class LogOnlineAnalysis(object): def __init__(self): pass def analyze(self, log_dir): print("Analyzing the log files under {}. online.".format(log_dir)) class Client(object): def __init__(self): pass def act(self): collect = LogOfflineCollection() collect.collect("C:\\cty\\logs\\") collect.collect("/opt/logs") print("=================================================") analysis = LogOnlineAnalysis() analysis.analyze("C:\\cty\\logs\\") analysis.analyze("/opt/logs") # if __name__ == '__main__': # client = Client() # client.act() # 依赖倒转原则(Dependence Inversion Principle):高层模块不应该依赖于底层模块, # 二者都应该依赖于抽象, # 优化代码 class Log(object): def __init__(self, name): self.name = name def collect(self, log_dir): pass class LogOfflineCollection(Log): def __init__(self, name="LogOfflineCollection"): super(LogOfflineCollection, self).__init__(name) def collect(self, log_dir): print("Collecting the log files under {}".format(log_dir)) class LogOnlineAnalysis(Log): def __init__(self, name="LogOnlineAnalysis"): super(LogOnlineAnalysis, self).__init__(name) def collect(self, log_dir): print("Collecting the log files under {}".format(log_dir)) class Client(object): # 这里也可以在细化。比如在离线计算群的客户端,在流计算群的客户端。也是采用依赖倒转原则 def __init__(self): pass def act(self): collect = LogOfflineCollection() collect.collect("C:\\cty\\logs\\") collect.collect("/opt/logs") print("=================================================") analysis = LogOnlineAnalysis() analysis.collect("C:\\cty\\logs\\") analysis.collect("/opt/logs") if __name__ == '__main__': client = Client() client.act()