码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式之享元模式

时间:2020-06-13 23:00:58      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:print   cto   实现   eth   nbsp   tac   meta   str   sel   

from abc import ABCMeta, abstractmethod


# 运用共享技术有效地支持大量细粒度对象的复用,类似于对象池模式,不过对象池是为了节省对象不断创建销毁的时间,
# 享元模式是为了防止重复创建相似或相同的对象,导致内存泄漏
# 两个主要角色:享元对象、享元工厂
class Flyweight(metaclass=ABCMeta):
    """享元类"""
    @abstractmethod
    def operation(self, extrinsicState):
        pass


class FlyweightImpl(Flyweight):
    """享元模式的具体实现类"""
    def __init__(self, color):
        self.__color = color

    def operation(self, extrinsicState):
        print("%s取得%s色颜料" %(extrinsicState, self.__color))


class FlyweightFactory:
    """享元工厂"""
    def __init__(self):
        self.__flyweights = {}

    def getFlyweight(self, key):
        pigment = self.__flyweights.get(key, FlyweightImpl(key))
        return pigment


def testFlywieght():
    factory = FlyweightFactory()
    pigmentRed = factory.getFlyweight("")
    pigmentRed.operation("梦之队")
    pigmentBlue = factory.getFlyweight("")
    pigmentBlue.operation("梦之队")
    pigmentBlue1 = factory.getFlyweight("")
    pigmentBlue1.operation("和平队")


testFlywieght()

 

设计模式之享元模式

标签:print   cto   实现   eth   nbsp   tac   meta   str   sel   

原文地址:https://www.cnblogs.com/loveprogramme/p/13122089.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!