跳到主要內容


Python-設計模式-單例模式

Python
設計模式
單例模式

Lazy初始化,指行緒不安全

class Singleton(object): 
   _instance = None
   def __new__(cls, *args, **kw):
      if not cls._instance: 
         cls._instance = super(Singleton, cls).__new__(cls, *args, **kw) 
         return cls._instance 

class MyClass(Singleton): 
   a = 1 

one = MyClass() 
two = MyClass() 
one == two 

沒Lazy初始化,指行緒安全

class Singleton1(object): 
   pass 

class Singleton2(Singleton1): 
   __instance = Singleton1() 
   def __new__(cls, *args, **kw): 
      return cls.__instance 


class MyClass2(Singleton2): 
   a = 2 

new_one = MyClass2()
new_two = MyClass2()

new_two == new_two 


程式碼說明

每個範例最後一行都是確認兩者是否相同
第一個範例用了if判斷_instance是否為空值,如果是,則實作物件,為Lazy初始化
第一個範例先定義singleton1,在singleton2直接實作在_instance,這是模仿java的做法,不確定執行緒安全與否。

留言

這個網誌中的熱門文章

程式語言學習概論(1)

程式語言 介紹

Python-設計模式-共享模式

Python 設計模式 共享模式 class Font:     def __init__(self):        self.Size = 0        self.Type = ''     def printAll(self):        print(self.Size, self.Type)  class FontFacotry:     def Word(self, Size=3, Type='1'):        F = Font()        F.Size = Size        F.Type = Type        return F  FontSize = [1,2,3] FontType = ['1','2','3'] Facotry = FontFacotry()  F1 = Facotry.Word(FontSize[0],FontType[0])  F1.printAll()  F2 = Facotry.Word( FontSize[1],FontType[1] ) F2.printAll()  F3 = Facotry.Word( FontSize[2],FontType[2] ) F3.printAll() 程式碼說明 font 定義類別 fontFacotry物件生成工廠 fontsize用來儲存font大小的外部空間 fonttype用來儲存font種類的外部空間

python-設計模式-策略模式

python 設計模式 策略模式 class Stragey:     def Algorithm(self):        pass class  Stragey1(Stragey):     def Algorithm(self):        print('run algorithm1')  class Stragey2(Stragey):     def Algorithm(self):        print('run algorithm2')  class A:     def __init__(self):        self.a = None     def SetAlgorithm(self, algorithm):        self.a = algorithm a = A() a.SetAlgorithm(Stragey1())  a.a.Algorithm()  a.SetAlgorithm(Stragey2())  a.a.Algorithm()  程式碼說明 定義策略模式,寫策略一、策略二類別,定義類別A,並設定可以存放不同策略之函數,執行上述功能。