您的位置:首页 > 编程语言 > Python开发

python设计模式-工厂模式

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

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

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息