单例模式与工厂模式--简解

单例模式

  • 保证系统中一个类只有一个实例而且该实例易于被外界访问,从而方便对实例个数的控制并节约系统资源
class Test(object):
    is_instance = None
    is_first = True

    def __new__(cls, *args, **kwargs):   ## 工厂方法,生成实例,控制实例的创建
        if cls.is_instance == None:
            cls.is_instance = object.__new__(cls)

        return cls.is_instance

    def __init__(self, name):  ## 实例方法,用来初始化实例属性
        if Test.is_first:
            self.name = name
            Test.is_first = False


test1 = Test('lf1')

print(id(test1))       # 2136967041656
print(test1.name)      # lf1

test2 = Test('lf2')     

print(id(test2))        # 2136967041656
print(test2.name)       # lf1

工厂模式

  • 简单工厂为例,它由一个工厂类根据传入的参数决定创建出哪一种产品类的实例,属于类的创建型模式
class Shape(object):
    def __init__(self):
        pass

    def draw(self):
        pass


class Triangle(Shape):
    def __init__(self):
        print("I am a triangle")

    def draw(self):
        print("I am drawing triangle")


class Rectangle(Shape):
    def __init__(self):
        print("I am a rectnagle")

    def draw(self):
        print("I am drawing triangle")


class Trapezoid(Shape):
    def __init__(self):
        print("I am a trapezoid")

    def draw(self):
        print("I am drawing triangle")


class Diamond(Shape):
    def __init__(self):
        print("I am a diamond")

    def draw(self):
        print("I am drawing triangle")


class ShapeFactory(object):
    shapes = {'triangle': Triangle, 'rectangle': Rectangle,
              'trapezoid': Trapezoid, 'diamond': Diamond}

    def __new__(cls, name):   # 相当于工厂 生成实例
        if name in ShapeFactory.shapes.keys():
            print("creating a new shape %s" % name)
            return ShapeFactory.shapes[name]()
        else:
            print("creating a new shape %s" % name)
            return Shape()

ShapeFactory('rectangle').draw()   ## 相当于 Rectangle().draw()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值