享元模式
class flower: def __init__(self): pass def buy(self): pass class ShareFlower(flower): def __init__(self, color): self.color = color def buy(self): print('一朵 %s 的鲜花' % (self.color)) class Factory(): def __init__(self): self.share = dict() def getFlower(self, color): if color not in self.share: print('not in') self.share[color] = ShareFlower(color) return self.share[color] class UnShareFlower(flower): def __init__(self, color): self.color = color def buy(self): print('不共享一朵 %s 的鲜花' % (self.color)) flower = Factory() blue_flower = flower.getFlower('blue') red_flower = flower.getFlower('red') red_flower1 = flower.getFlower('red') red_flower2 = flower.getFlower('red') black_flower = UnShareFlower('blak') blue_flower.buy() red_flower.buy() red_flower1.buy() red_flower2.buy() black_flower.buy()
单例模式是类级别的,一个类只能有一个对象实例;
享元模式是对象级别的,可以有多个对象实例,多个变量引用同一个对象实例;
享元模式主要是为了节约内存空间,提高系统性能,而单例模式主要为了可以共享数据;