python 简单工厂模式,python工厂模式使用



abc 是抽象类模块
abc.ABC 是继承抽象类  也可直接继承 (metaclass=ABCMeta)
abc.abstractmethod 是定义抽象方法


简单工厂模式:通过接口创建对象,但不会暴露对象创建逻辑


在设计模式中主要用于抽象对象的创建过程,让用户可以指定自己想要的对象而不必关心对象的实例化过程。
这样做的好处是用户只需通过固定的接口而不是直接去调用类的实例化方法来获得一个对象的实例,隐藏了实例创建过程的复杂度,
解耦了生产实例和使用实例的代码,降低了维护的复杂性。
http请求共6种(get,post,put,delete,options,head),现在我们用工厂模式来生成不同的请求对象.

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')

 

相关内容

    暂无相关文章

评论关闭