工厂设计模式

 

 

这个和简单工厂有区别,简单工厂模式只有一个工厂,工厂方法模式对每一个产品都有相应的工厂

  好处:增加一个运算类(例如N次方类),只需要增加运算类和相对应的工厂,两个类,不需要修改工厂类。

  缺点:增加运算类,会修改客户端代码,工厂方法只是把简单工厂的内部逻辑判断移到了客户端进行。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

class Operation(object):
    """
    抽象类
    """
def GetResult(self): raise NotImplemented
class Add(Operation): """ """
def GetResult(self, numa, numb): return numa + numb

class OperationFactory(object): """ 工厂类 """
def CreateOperation(self): raise NotImplemented
class AddFactory(OperationFactory): def CreateOperation(self): return Add()
if __name__ == '__main__': obj = AddFactory() ret = obj.CreateOperation() result = ret.GetResult(2,5) print(result)

 

posted @ 2016-10-31 20:09  我当道士那儿些年  阅读(215)  评论(0编辑  收藏  举报