每日一题 为了工作 2020 0427 第五十六题

//设计模式 python版本的简单工厂模式 和 单例模式

# coding=utf-8
# 简单工厂模式

class Ace(object):

    def __init__(self,name):
        self.name = name

    def cut_tree(self):
        print("使用"+self.name+"砍树")

class Stone(Ace):

    def __init__(self):
        pass

    def cut_tree(self):
        print("使用石头去砍树")

class Stell(Ace):

    def __init__(self):
        pass

    def cut_tree(self):
        print("使用钢铁开始砍树")


class Factory(object):

    @staticmethod
    def getAce(ace_type):
        if "stone" == ace_type:
            return Stone()
        elif "stell" == ace_type:
            return Stell()
        else:
            return Ace()

class Worker(object):

    def __init__(self,worker_name,ace_type):
        self.worker_name = worker_name
        self.ace_type = ace_type

    def work_action(self):
        ace = Factory.getAce(self.ace_type)
        print(self.worker_name)
        ace.cut_tree()

if __name__ == '__main__':

    work = Worker("zhangsna","stone")
    work.work_action()

  

# coding=utf-8
# 单例设计模式

class Singleton:
    instance = None
    firstInit = True

    def __init__(self,name):
        if self.firstInit:
            print("init")
            self.firstInit = False
            self.name = name

    def __new__(cls, name,*args, **kwargs):
        if not cls.instance:
            cls.instance = object.__new__(cls)
        return cls.instance

    def run(self):
        print("{0} is run".format(self.name))


if __name__ == '__main__':
    s1 = Singleton("zs")
    s2 = Singleton("ls")

    print(id(s1))
    print(id(s2))
    s1.run()
    s2.run()

  

posted @ 2020-04-27 17:00  雪瞳  阅读(165)  评论(0编辑  收藏  举报