abc 是抽象类模块
abc.ABC 是继承抽象类 也可直接继承 (metaclass=ABCMeta)
abc.abstractmethod 是定义抽象方法
简单工厂模式:通过接口创建对象,但不会暴露对象创建逻辑
在设计模式中主要用于抽象对象的创建过程,让用户可以指定自己想要的对象而不必关心对象的实例化过程。
这样做的好处是用户只需通过固定的接口而不是直接去调用类的实例化方法来获得一个对象的实例,隐藏了实例创建过程的复杂度,
解耦了生产实例和使用实例的代码,降低了维护的复杂性。
http请求共6种(get,post,put,delete,options,head),现在我们用工厂模式来生成不同的请求对象.
-------欢迎加入python新手交流群851211580-------
import abc
class Method(abc.ABC):
@abc.abstractmethod
def request(self, url):
pass
class Get(Method):
def request(self, url):
print("Get 请求地址:%s" % url)
class Post(Method):
def request(self, url):
print("Post 请求地址:%s" % url)
class Delete(Method):
def request(self, url):
print("Delete 请求地址:%s" % url)
# 生产对象
class MethodFactory:
def create(self, method_name) -> Method:
return eval(method_name)()
if __name__ == '__main__':
factory = MethodFactory()
method = factory.create('Get')
get = method.request('http://www.baidu.com')
最后多说一句,小编是一名python开发工程师,这里有我自己整理了一套最新的python系统学习教程,包括从基础的python脚本到web开发、爬虫、数据分析、数据可视化、机器学习等。想要这些资料的可以关注小编,并在后台私信小编:“01”即可领取。