策略模式
模式说明
定义算法家族并且分别封装,它们之间可以相互替换而不影响客户端。
模式结构图
程序示例
说明:选择不同排序算法
代码:
class OrderStrategy(object): """sort base""" def Sort(self,*args): pass class Bubble(OrderStrategy): def Sort(self,args): args = list(args) length = len(args) for i in range(length): j = i + 1 while j < length : if args[i] > args[j]: args[i],args[j] = args[j],args[i] j = j + 1 print "Bubble:" print args return args class Insertion(OrderStrategy): def Sort(self,args): args = list(args) length = len(args) for i in range(1,length): temp = args[i] #for j in range(i,-1,-1):#range don't contain the stop element so the middl -1 means stop at 0 # if args[j - 1] > temp and j>0: # args[j] = args[j - 1] # else: # break j=i; while j>0: if args[j - 1] > temp: args[j] = args[j - 1] j=j-1; else: break args[j] = temp #asignment the current (position i) element to j(the first element less than it on the left side of i) print "Insertion:" print args return args class Selection(OrderStrategy): def Sort(self,args): #print args args = list(args) #print args length = len(args) smallValue = 0 smallLocation = 0 for i in range(0,length): #assume the smallest element and positon smallValue = args[i] smallLocation = i #find the truly smallest element and position for j in range(i + 1,length): if args[j] < smallValue: smallValue = args[j] smallLocation = j #exchange smallest element and current (position i) element args[i],args[smallLocation] = args[smallLocation],args[i] print "Selection:" print args return args class SortHandler(object): strategy = OrderStrategy() def SetStrategy(self,strategy): self.strategy = strategy def sort(self,args): self.strategy.Sort(args) sortList = (3,1,4,2,6) if __name__ == '__main__': handler = SortHandler() handler.SetStrategy(Selection()) handler.sort(sortList) handler.SetStrategy(Insertion()) handler.sort(sortList) handler.SetStrategy(Bubble()) handler.sort(sortList)
运行结果:
参考来源:
http://www.cnblogs.com/chenssy/p/3679190.html
http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html
http://www.cnblogs.com/wangjq/archive/2012/07/03/2570344.html