python工厂模式 简书_python工厂模式构建实例

实现一个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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值