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()
    

      

  • 相关阅读:
    洛谷 P2384 最短路
    洛谷 P2910 [USACO08OPEN]寻宝之路Clear And Present Danger
    POJ 3264 Balanced Lineup
    洛谷 P1892 团伙
    洛谷 P1724 东风早谷苗
    P1129 [ZJOI2007]矩阵游戏
    P1894 [USACO4.2]完美的牛栏The Perfect Stall
    Poj 3041 Asteroids
    P3377 【模板】左偏树(可并堆)
    P1613 跑路
  • 原文地址:https://www.cnblogs.com/walxt/p/12787944.html
Copyright © 2011-2022 走看看