记录一下Python学习中的点滴,分享一段代码。
【问题背景】在不同的系统平台需要执行一段有差异的指令,该如何写出更优雅的代码?
【知识点】依赖倒置原则 + 简单工厂模式
【代码分享】
#!/usr/bin/env python
# coding:utf-8
"""
依赖倒置原则 + 简单工厂模式
@Date: 2023/4/5 16:44
@Author: zhangbc
@Version: 1.0.0
@Contact: zhangbocheng189@163.com
@Description:
"""
import os
from abc import ABCMeta, abstractmethod
class IOperator(metaclass=ABCMeta):
"""
系统操作接口
"""
@abstractmethod
def operate(self, system):
pass
class System(metaclass=ABCMeta):
"""
系统抽象类
"""
def __init__(self, name):
self.name = name
@abstractmethod
def run(self):
pass
class SystemFactory:
def __init__(self, name):
self.name = name
def create(self):
return {
'posix': PosixSystem(self.name),
'nt': WindowsSystem(self.name),
'default': UnixSystem(self.name)
}.get(self.name, 'default')
class UnixSystem(System):
def run(self):
print('This is Unix System,', self.name)
class WindowsSystem(System):
def run(self):
print('This is Windows System,', self.name)
class PosixSystem(System):
def run(self):
print('This is MacOS System,', self.name)
class Operator(IOperator):
def operate(self, system):
print(f'The is driver of {system.name}')
system.run()
if __name__ == '__main__':
print('========依赖倒置原则============')
unix = UnixSystem('Unix')
wind = WindowsSystem('Windows')
macOS = PosixSystem('MacOS')
ds = Operator()
ds.operate(unix)
ds.operate(wind)
ds.operate(macOS)
print('\n\n========简单工厂设计模式===========')
_os = SystemFactory(os.name).create()
ds.operate(_os)