設計模式(design pattern)是一套被反覆使用、多數人知曉的、經過分類的、**設計經驗的總結。 使用設計模式的目的:為了**可重用性、讓**更容易被他人理解、保證**可靠性。 設計模式使**編寫真正工程化;設計模式是軟體工程的基石脈絡,如同大廈的結構一樣。所有的設計模式示例都是**於 菜鳥教程 ,每個設計模式的uml都可以在菜鳥教程中找到相應的示例工廠模式在菜鳥教程中的uml圖為
工廠模式在github中的**為:
import abc
class shape(metaclass=abc.abcmeta):
@abc.abstractmethod
def draw(self):
pass
class circle(shape):
def draw(self):
print("inside rectangle::draw() method.")
class square(shape):
def draw(self):
print("inside square::draw() method.")
class rectangle(shape):
def draw(self):
print("inside circle::draw() method.")
class shapefactory(object):
def getshape(self, shapetype):
if shapetype=="circle":
return circle()
elif shapetype=="rectangle":
return rectangle()
elif shapetype=="square":
return square()
else:
return none
if __name__ == '__main__':
'''工廠模式的優點:
1. 乙個呼叫者想建立乙個物件,只要知道其名稱
2. 擴充套件性高,如果想增加乙個產品,只要擴充套件乙個工廠類就可以
3. 遮蔽產品的具體實現,呼叫者只關心產品的介面
'''shapefactory = shapefactory()
# 獲取cicle、rectangle、square的物件
shape1 = shapefactory.getshape("circle")
shape2 = shapefactory.getshape("rectangle")
shape3 = shapefactory.getshape("square")
#分別呼叫draw()方法
shape1.draw()
shape2.draw()
shape3.draw()
在main的注釋部分我會給出該設計模式的優點,並且在main中給出該示例的客戶端呼叫 設計模式(python) 程式設計原則
開放 封閉原則規定,類或物件及其方法對於擴充套件來說,應該是開放的,但是對於修改來說,應該是封閉的。簡單地說,這意味著當你開發軟體應用的時候,一定確保以通用的方式來編寫類或模組,以便每當需要擴充套件類或物件行為的時候不必修改類本身。相反,類的簡單擴充套件將有助於建立新的行為。例如,開放 封閉原則能夠...
Python 程式設計 單例模式
單例模式 singleton pattern 屬於建立型模式,它提供了一種建立物件的最佳方式。這種模式涉及到乙個單一的類,該類負責建立自己的物件,同時確保只有單個物件被建立,並提供一種訪問其唯一物件的方式。特點 1.單例類只能有乙個例項 2.單利類必須自己建立自己的唯一例項 3.單例類必須給其他物件...
python函式式程式設計模式 python函式式程式設計
1 callable內建函式判斷乙個名字是否為乙個可呼叫函式 import math x 1 y math.sqrt callable x false callable y true 2 記錄函式 文件字串 def square x calculates the square of number x...