美文网首页
sigleton in python

sigleton in python

作者: 将军红 | 来源:发表于2019-12-19 17:09 被阅读0次
# coding = utf-8
import sys


# 1. Sigleton
# 1.1 use decrators
def sigleton(cls, *args, **kwargs):
    instance = {}

    def _get_instance():
        if cls not in instance:
            instance[cls] = cls(*args, **kwargs)
        return instance[cls]
    return _get_instance


# test
@sigleton
class BaseClass(object):
    pass

a1 = BaseClass()
print a1
a2 = BaseClass()
print a2


# 1.2 use __new__
class sigleton2(object):

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '__instance__'):
            orig = super(sigleton2, cls)
            cls.__instance__ = orig.__new__(cls, *args, **kwargs)
        return cls.__instance__

    """
    class C(B):
        def meth(self, arg):
            super(C, self).meth(arg)
    """


# test
b1 = sigleton2()
b2 = sigleton2()
print 'b1=b2?', b1 is b2


# 2. strategy
class StrategyOne(object):
    @classmethod
    def operation(cls):
        print 'operation in StrategyOne'


class StrategyTwo(object):
    @classmethod
    def operation(cls):
        print 'operation in StrategyTwo'


class Strategy(object):
    def __init__(self, contex, StrategyOne, StrategyTwo):
        self.contex = contex
        self.StrategyOne = StrategyOne
        self.StrategyTwo = StrategyTwo

    def operation(self):
        if self.contex == 'contex_for_one':
            self.StrategyOne.operation()
        elif self.contex == 'contex_for_two':
            self.StrategyTwo.operation()
        else:
            raise Exception('ContexError in __init__')


# test for Strategy
s1 = Strategy('contex_for_one', StrategyOne, StrategyTwo)
s1.operation()

相关文章

网友评论

      本文标题:sigleton in python

      本文链接:https://www.haomeiwen.com/subject/okqvnctx.html