python工厂模式构建实例

2020-08-08  本文已影响0人  卜是

实现一个python类作为统一的接口,来创建具体类的对象。
1. 工厂类

from shape_line import *
from shape_rect import *
from shape_circle import *
factory_register = {
'line' : shape_line,
'rect' : shape_rect,
'circle' : shape_circle
}
class Shape_Factory:
    def create_shape(self,type_name):
        print('create {} shape'.format(type_name))
        if type_name in factory_register:
            return factory_register[type_name]()
        return None

shape_factory = Shape_Factory()

2. 基类

'''shape base类, shape_base.py'''
class shape_base():
    def __init__(self):
        self.label_name = "base"
        self.output_shape = None
    def _set_label_name_related(self):
        self.loss = 'loss_{}'.format(self.label_name)  
        self.acc = '{}_acc'.format(self.label_name)
    def get_labels(self):
        return self.labels

3. 具体子类

'''shape_line.py文件'''
from shape_base import *
class shape_line(shape_base):
    def __init__(self):
        super().__init__()
        self.label_name = "line"
        super()._set_label_name_related()
    def shape_draw(self):
        '''do something'''
        return self.output_shape

4. main函数测试

from shape_factory import shape_factory
if __main__ == '__main__':
    shape_ids = ['line', 'rect', 'circle']
    shapes = [shape_factory.create_shape(item) for item in shape_ids]
上一篇 下一篇

猜你喜欢

热点阅读