会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132431个问题
Python 全系列/第一阶段:Python入门/编程基本概念 3841楼
Python 全系列/第一阶段:Python入门/编程基本概念 3842楼
Python 全系列/第一阶段:Python入门/编程基本概念 3844楼
Python 全系列/第一阶段:Python入门/编程基本概念 3845楼

class ComputerFactory:
    __obj = None
    __flag = True
    def __new__(cls, *args, **kwargs):
        if cls.__obj == None:                    #使用单例模式控制工厂对象的数量为1
            cls.__obj = object.__new__(cls)
        return cls.__obj
    def __init__(self):
        if ComputerFactory.__flag:              #使用单例模式初始化1次对象
            self.__flag = False
    def create_computer(self,name):
        if name == '联想':
            return Lenvo().calculate()
        elif name == '华硕':
            return HuaShuo().calculate()
        elif name == '神舟':
            return ShenZhou().calculate()
        else:
            return '品牌不存在'
class Computer:
    def calculate(self):
        print('身为品牌电脑,我们都有独自的logo')
class Lenvo(Computer):
    print('联想1')
    def calculate(self):
        print('我是联想电脑,我的logo就是《》《》《》')
class HuaShuo(Computer):
    print('华硕2')
    def calculate(self):
        print('我是华硕电脑,我的logo就是0 。0')
class ShenZhou(Computer):
    print('神舟3')
    def calculate(self):
        print('我是神舟电脑,我的logo就是東風快递,使命必达!')
fac = ComputerFactory()
fac2 = ComputerFactory()
c1 = fac.create_computer('华硕')
# c2 = fac2.create_computer('神舟')
print(fac._ComputerFactory__obj,1)
print(fac2._ComputerFactory__obj,2)
print(fac._ComputerFactory__flag,1)
print(fac2._ComputerFactory__flag,2)
print(fac2 is fac)


image.png

Python 全系列/第一阶段:Python入门/面向对象 3846楼
Python 全系列/第一阶段:Python入门/序列 3849楼
Python 全系列/第一阶段:Python入门/控制语句 3851楼
Python 全系列/第一阶段:Python入门/编程基本概念 3854楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637