Python設計模式

簡單的來說下python的單例模式和工廠模式,工廠模式我們來介紹簡單工廠模式,抽象工廠模式感興趣的可以自己去了解。

一、單例模式:

舉個常見的單例模式例子,我們日常使用的電腦上都有一個回收站,在整個操作系統中,回收站只能有一個實例,整個系統都使用這個唯一的實例,而且回收站自行提供自己的實例。因此回收站是單例模式的應用。簡單的來說就是確保某一個類只有一個實例,而且自行實例化並向整個系統提供這個實例,這個類稱爲單例類,單例模式是一種對象創建型模式。

Demo:

class Single():
    __instance = None
    __flag = False
    def __new__(cls, name, age):
        if not cls.__instance:#當此類沒有實例時才進行創建
            cls.__instance = object.__new__(cls)
        return cls.__instance
    def __init__(self, name, age):
        if not self.__flag:
            self.__flag = True
            self.name = name
            self.age = age
    def __str__(self):
        toString = '我是'+self.name+',我的年齡是'+str(self.age)
        return toString
s1 = Single('SKH', 18)
s2 = Single('ZXX', 18)
print(s1)
print(s2)

輸出:

我是SKH,我的年齡是18
我是SKH,我的年齡是18

Process finished with exit code 0

二、簡單工廠模式:

工廠模式是我們最常用的實例化對象模式了,是用工廠方法代替new操作的一種模式。雖然這樣做,可能多做一些工作,但會給你係統帶來更大的可擴展性和儘量少的修改量(可維護性)。

 簡單工廠模式:Simple Factory模式不是獨立的設計模式,他是Factory Method模式的一種簡單的、特殊的實現。他也被稱爲靜態工廠模式,通常創建者的創建方法被設計爲static方便調用。

Demo:

class Person():
    def __init__(self, name):
        self.name = name
    def work(self, type):
        print(self.name+"開始工作了")
        axe = Factory.axeType(type)
        axe.cut()
class Axe():
    def __init__(self):
        pass
class StoneAxe(Axe):
    def __init__(self):
        pass
    def cut(self):
        print('使用石斧砍樹')
class SteelAxe(Axe):
    def __init__(self):
        pass
    def cut(self):
        print('使用鐵斧來砍樹')
class Factory():
    @staticmethod
    def axeType(type):
        if 'stone' == type:
            return StoneAxe()
        elif 'steel' == type:
            return SteelAxe()
        else:
            return 'Error'
p1 = Person('zs')
p1.work('stone')
p2 = Person('ls')
p2.work('steel')

輸出:

zs開始工作了
使用石斧砍樹
ls開始工作了
使用鐵斧來砍樹

Process finished with exit code 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章