python设计模式-工厂模式

来源:互联网 发布:cctv5直播软件 编辑:程序博客网 时间:2024/05/21 10:13

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

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


1. 工厂方法

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

import xml.etree.ElementTree as etreeimport jsonclass 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    #XMLConnectordef connect_to(filepath):    factory = None    try:        factory = connection_factory(filepath)    except ValueError as ve:        raise ValueError('Can not connect to ()'.format(filepath))    return factorydef 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      



0 0