python的设计模式

时间:2023-04-27
本文章向大家介绍python的设计模式,主要内容包括设计模式、一、什么是设计模式、二、python实现设计模式、创建型模式、1.单例模式、2.工厂模式、使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

设计模式

一、什么是设计模式

软件工程中,设计模式是指软件设计问题的推荐方案。设计模式一般是描述如何组织代码和使用最佳实践来解决常见的设计问题。需要记住一点:设计模式是高层次的方案,并不关注具体的实现细节,比如算法和数据结构。对于正在尝试解决的问题,何种算法和数据结构最优,则是由软件工程自己把我

二、python实现设计模式

设计模式共分为三类

  • 创建型模式
  • 结构性模式
  • 行为型模式

创建型模式

1.单例模式

单例模式(Singleton Pattern)是一个常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在,当希望在某个系统中只出现一个实例时,单例对象就能派上用场。

class Singleton():
    _instance = None # 定义一个变量,来接收实例化对象
    def __new__(cls, *args,**kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance
   
s1 = Singleton()
s2 = Singleton()
print(id(s1),id(s2))

2.工厂模式

在工厂模式设计中,客户端可以请求一个对象,而无须知道这个对象来自哪里(使用类来生成对象)。工厂背后的思想是简化对象的创建,基于一个中心化的函数来实现创建对象,更易于追踪创建了哪些对象。通过将创建的代码和使用对象的代码解耦,工厂能够降低应用维护的复杂度。

在工厂方法中,通过执行单个函数,传入一个参数(表明想要什么),但是并不要求知道对象是如何实现以及对象来自来

# 基类
class Person()
	def __init__(self):
    	self.name = None
    	self.gender = None
	def getName(self):
        return self.name
    
    def getGender(self):
        return self.gender

#
class Male(Person):
    def __init__(self,name):
        # super().__init__()
        print(name)

class Female(Person):
    def __init__(self,name):
        # super().__init__()
        print(name)

class Factory():
    def getPerson(self,name,gender):
        if gender == "M":
            return Male(name)
        if gender =="F":
            return Female(name)
        
if __name__ == '__main__':
    factory = Factory()
    person = factory.getPerson("Waltz","M")

原文地址:https://www.cnblogs.com/wei0919/p/17360484.html