设计模式之组合模式
设计模式之组合模式
from abc import ABCMeta,abstractmethod # ---------------------构造一个标准类 class Draw(metaclass=ABCMeta): @abstractmethod def draw(self): pass @abstractmethod def add(self,draw): pass @abstractmethod def getchildren(self): pass # 注意本环境是在二维环境下实现的,其他环境可自行实现 # ---------------------构造一个点 class Point(Draw): # 点,平面上的点用一个坐标来表示 def __init__(self,x,y): self.x = x self.y = y def draw(self): print(self) def add(self,draw): # 点的坐标是唯一的 raise TypeError def getchildren(self): return [self.x,self.y] def __str__(self): return '点: (%s, %s)'%(self.x,self.y) # --------------------构造一个线 class Line(Draw): #线,线用两个点来表示 def __init__(self,point1,point2): self.ponit1 = point1 self.ponit2 = point2 self.k = (self.ponit2.y - self.ponit1.y) / (self.ponit2.x - self.ponit1.x) def draw(self): print(self) def add(self,draw): raise TypeError def getchildren(self): return [self.ponit1,self.ponit2] def __str__(self): return '线:[%s, %s]'%(self.ponit1,self.ponit2) # --------------------构造一个面 class Surface(Draw): def __init__(self): self.children = dict() def add(self,draw): self.children[draw] = draw def getchildren(self): return self.children def draw(self): print(self) def __str__(self): return str({str(v) for v in self.children.values() }) # 构造一个面 surface = Surface() p1 = Point(1,2) p2 = Point(0,0) p3 = Point(3,2) p4 = Point(2,6) line1 = Line(p1,p2) line2 = Line(p3,p4) surface.add(line1) surface.add(line2) surface.draw() # line1.draw()
刷初步设计被拆包时间戳