python基础学习:类3程序模式

【单例模式 】

原理:

class test(object):
    __instance = None
    def __new__(cls):
        if cls.__instance == None:
            cls.__instance = object.__new__(cls)
            return cls.__instance
        else:
            return cls.__instance

t = test()

#通过私有属性在__new__创建里面判断为空不,为空就通过object基类创建一个对象,创建对象后就不为空了
#下次再定义对象的时候,进类执行__new__判断不为空,返回第一个创建的对象

__new__(cls):方法是进入类时第一个调用的方法,它有返回值对象是object . __new__(cls),

 

单例1、

##单例模式之只初始化一次对象
# class temp(object):
#
#     __instance = None
#     __init_flag = False
#
#     def __new__(cls,name):
#         if cls.__instance == None:
#             cls.__instance = object.__new__(cls)
#             return cls.__instance
#         else:
#             return cls.__instance
#
#     def __init__(self,name):
#         if temp.__init_flag == False:
#             self.name = name
#             temp.__init_flag = True
#
# a = temp("A")
# print(id(a))
# print(a.name)

 

 

 

【工厂模式】

#简单的工厂模式#买车
class CarStore(object):
    def __init__(self):
        self.type = Factory()#实列化对象,在类里面调用其他外部类
    def order(self,benben):
       return self.type.select_car_type(benben)#调用其他类对象里面的方法

class Factory(object):
    def select_car_type(self,car_type):
        if car_type == "A":
            return carA()   #在类里面调用其他外部类
        elif car_type == "B":
            return carB()
        elif car_type == "C":
            return carC()

class Car(object):
    def move(self):
        print("car move")
    def stop(self):
        print("car stop")

class carA(Car):
    print("carA")
class carB(Car):
    print("carB")
class carC(Car):
    print("carC")

car_store = CarStore()      #创建类对象
car = car_store.order("A")  #car_store.order("A")返回的是carA()  创建对象
car.move()      #carA()是Car()的子类,它拥有父类的属性
car.stop()

#通过类里面调用类外的类,传递参数信息,最后拿到的那个信息决定了要实现的功能

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值