外卖网站 模板,兰陵住房建设局网站,网站建设的完整流程图,美食网站 源码Python语言之“工厂函数“”与“多态方式”的异同分析探究#xff01;
工厂函数确实常常利用多态来创建对象#xff0c;但它们不是同一个概念。
让我用对比的方式解释#xff1a;
1. 相同点#xff1a;都涉及多种类型
# 多态#xff1a;不同类型响应相同的方法
class Anim…Python语言之“工厂函数“”与“多态方式”的异同分析探究工厂函数确实常常利用多态来创建对象但它们不是同一个概念。让我用对比的方式解释1.相同点都涉及多种类型# 多态不同类型响应相同的方法classAnimal:defmake_sound(self):passclassDog(Animal):defmake_sound(self):returnWoof!十一剑的CS_DN博客classCat(Animal):defmake_sound(self):returnMeow!# 工厂函数创建不同类型的对象defcreate_animal(animal_type):ifanimal_typedog:returnDog()elifanimal_typecat:returnCat()2.关键区别a. 关注点不同# 多态关注行为的多样性classPaymentMethod:defpay(self,amount):passclassCreditCard(PaymentMethod):defpay(self,amount):print(f信用卡支付 ${amount})十一剑的CS_DN博客classPayPal(PaymentMethod):defpay(self,amount):print(fPayPal支付 ${amount})# 工厂函数关注创建的多样性classPaymentFactory:defcreate_payment(self,method):ifmethodcredit_card:returnCreditCard()elifmethodpaypal:returnPayPal()# 客户端代码使用多态defprocess_payment(payment_method,amount):payment_method.pay(amount)# 多态不同支付方式统一接口# 使用工厂创建对象factoryPaymentFactory()paymentfactory.create_payment(credit_card)process_payment(payment,100)# 然后使用多态调用b. 时间点不同# 多态发生在运行时动态绑定classShape:defdraw(self):pass十一剑的CS_DN博客classCircle(Shape):defdraw(self):print(绘制圆形)classSquare(Shape):defdraw(self):print(绘制方形)# 工厂函数在创建时就决定了类型defcreate_shape(shape_type):ifshape_typecircle:returnCircle()# 创建时就确定了是圆形elifshape_typesquare:returnSquare()# 创建时就确定了是方形# 多态调用时才确定具体行为shapes[create_shape(circle),create_shape(square)]forshapeinshapes:shape.draw()# 多态运行时才知道调用哪个draw方法3.更清晰的对比表特性多态工厂函数主要目的统一接口不同实现创建对象关注点对象的行为对象的创建时间点运行时方法调用时创建时对象实例化时核心机制继承 方法重写条件判断 构造函数调用代码位置类的定义中独立的函数或类中4.工厂函数内部如何使用多态fromabcimportABC,abstractmethod# 1. 定义接口多态的基础classLogger(ABC):abstractmethoddeflog(self,message):pass十一剑的CS_DN博客# 2. 具体实现多态的具体表现classFileLogger(Logger):deflog(self,message):withopen(app.log,a)asf:f.write(message\n)classConsoleLogger(Logger):deflog(self,message):print(f[LOG]{message})classDatabaseLogger(Logger):deflog(self,message):# 模拟数据库写入print(f写入数据库:{message})# 3. 工厂函数利用多态创建对象defcreate_logger(logger_type,**kwargs):工厂函数根据类型创建不同的日志器iflogger_typefile:returnFileLogger()eliflogger_typeconsole:returnConsoleLogger()eliflogger_typedatabase:returnDatabaseLogger()else:# 可以返回默认实现returnConsoleLogger()# 4. 客户端代码完全基于多态defprocess_data(data,logger):不关心logger的具体类型只关心它有log方法# 处理数据...logger.log(f开始处理数据:{data})# 多态调用# 更多处理...logger.log(数据处理完成)# 使用工厂创建 多态使用logger1create_logger(file)logger2create_logger(console)process_data(用户数据,logger1)# 写入文件process_data(系统数据,logger2)# 输出到控制台5.open()函数的具体分析# open() 函数内部实现概念上的伪代码defopen(file,moder,**kwargs):# 工厂函数的逻辑根据条件创建不同对象ifbinmode:# 二进制模式ifrinmode:returnBufferedReader(file,**kwargs)# 多态返回BufferedReaderelifwinmode:returnBufferedWriter(file,**kwargs)# 多态返回BufferedWriterelse:# 文本模式ifrinmode:returnTextIOWrapper(file,**kwargs,moder)# 多态返回TextIOWrapperelifwinmode:returnTextIOWrapper(file,**kwargs,modew)# 多态返回TextIOWrapper# 所有返回的对象都有 read()/write() 等方法多态的基础6.更复杂的例子工厂函数返回多态对象# 1. 多态接口classDataStore(ABC):abstractmethoddefsave(self,key,value):passabstractmethoddefload(self,key):pass# 2. 具体实现classFileStore(DataStore):def__init__(self,filename):self.filenamefilenamedefsave(self,key,value):withopen(self.filename,a)asf:f.write(f{key}:{value}\n)defload(self,key):withopen(self.filename,r)asf:forlineinf:k,vline.strip().split(:)ifkkey:returnvreturnNoneclassMemoryStore(DataStore):def__init__(self):self.data{}defsave(self,key,value):self.data[key]valuedefload(self,key):returnself.data.get(key)# 3. 工厂函数可以包含更多创建逻辑defcreate_store(store_type,**config):ifstore_typefile:returnFileStore(config.get(filename,data.txt))elifstore_typememory:returnMemoryStore()elifstore_typeredis:# 可以轻松扩展# 假设我们后面添加了RedisStorereturnRedisStore(config.get(host,localhost))else:raiseValueError(f不支持的存储类型:{store_type})# 4. 客户端代码完全多态defprocess_user_data(user_id,data,store):不关心store的具体类型只要它有save和load方法# 保存数据store.save(fuser_{user_id},data)# 多态调用# 读取数据loadedstore.load(fuser_{user_id})# 多态调用returnloaded十一剑的CS_DN博客# 5. 使用file_storecreate_store(file,filenameusers.txt)memory_storecreate_store(memory)# 相同的接口不同的实现多态result1process_user_data(1,Alice,file_store)result2process_user_data(2,Bob,memory_store)敲黑板十一剑的CS_DN博客祝您天天进步工厂函数和多态是互补的常常一起使用工厂函数是创建者负责根据条件创建合适的对象隐藏对象创建的复杂性多态是使用者让不同对象可以用相同接口操作隐藏对象类型的差异性典型流程工厂函数创建对象 → 对象具有多态接口 → 客户端代码通过多态接口使用对象总结如下工厂函数确实常常返回支持多态的对象这样客户端代码可以统一处理这些对象而不用关心它们的具体类型。但两者是不同层次的概念多态是关于接口设计的工厂函数是关于对象创建的