zoukankan      html  css  js  c++  java
  • 每日一题 为了工作 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()
    

      

  • 相关阅读:
    (JS/JQ)与Ajax
    JS与JQ的DOM处理
    正则表达式
    JS事件大全
    CSS(初级)学习笔记
    HTML学习笔记
    leetcode记录——65. 有效数字
    dp专题
    Hackerrank---A stones game
    组合博弈问题
  • 原文地址:https://www.cnblogs.com/walxt/p/12787944.html
Copyright © 2011-2022 走看看