python设计模式-工厂模式

    在工厂设计模式中,客户端可以请求一个对象,但是不用根据对象来自哪里,工厂根据不同的需要返回不同的对象(也就是说,工厂模式的中心思想是简化对象的创建

    工厂通常有两种形式,工厂方法和抽象工厂,工厂方法对不同的输入参数返回不同的对象;抽象工厂是一组用于创建一系列相关对象的工厂方法。


1. 工厂方法

    对不同的输入返回不同的对象

import xml.etree.ElementTree as etree
import json

class JSONConnector:
    def __init__(self, filepath):
        #具体初始化
    def parsed_data(self):
        #返回获取的数据
        
class XMLConnector:
    def __init__(self, filepath):
        #具体初始化
    def parsed_data(self):
        #返回获取的数据
        
def connection_factory(filepath):
    #if JSON file
    #JSONConnector
    #elif XML file
    #XMLConnector

def connect_to(filepath):
    factory = None
    try:
        factory = connection_factory(filepath)
    except ValueError as ve:
        raise ValueError('Can not connect to ()'.format(filepath))
    return factory

def main():
    factory = connect_to(filepath)


2. 抽象工厂

    是一组创建用于创建一系列相关对象的工厂方法

class Frog:
    def __init__(self, name):
    def __str__(self):
    def interact_with(self, obstacle):

class Bug:
    def __str__(self):
    def action(self):

class FrogWorld:
    def __init__(self, name):
    def __str__(self):
    def make_charactor(self):
    def make_obstacle(self):
#-----------------------------
class Wizard:
    def __init__(self, name):
    def __str__(self):
    def interact_with(self, obstacle):

class Ork:
    def __str__(self):
    def action(self):

class WizardWorld:
    def __init__(self, name):
    def __str__(self):
    def make_charactor(self):
    def make_obstacle(self):
#-----------------------------
class GameEnvironment:
    def __init__(self, factory):
        self.hero = factory.make_charactor()
        self.obstacle = factory.make_obstacle()
    
    def play(self):
        self.hero.interact_with(self.obstacle)
#-----------------------------
def main():
    #if 条件一
    #game = FrogWorld
    #elif 条件二
    #game = WizardWorld      



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值