当前位置: 移动技术网 > IT编程>脚本编程>Python > python 简单工厂模式

python 简单工厂模式

2019年09月24日  | 移动技术网IT编程  | 我要评论

方姚子毅,我们无处安放的青春txt,邯郸骑友大本营


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

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网