手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Python设计模式 之 简单工厂模式

[日期:2014-10-11] 来源:Linux社区  作者:lr982330245 [字体:大 中 小]

Python简单工厂模式属于类的创建型模式,适合用来对大量具有共同接口的类进行实例化,它可以推迟到运行的时候才动态决定要创建哪个类的实例,而不是在编译时就必须知道要实例化哪个类。

Python:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
 
class Circle(object): 
    def draw(self): 
        print 'draw circle' 
 
class Rectangle(object): 
    def draw(self): 
        print 'draw Rectangle' 
 
class ShapeFactory(object): 
    def create(self, shape): 
        if shape == 'Circle': 
            return Circle() 
        elif shape == 'Rectangle': 
            return Rectangle() 
        else: 
            return None 
 
fac = ShapeFactory() 
obj = fac.create('Circle') 
obj.draw() 

c++:

#include <iostream> 
#include <string.h> 
using namespace std; 
 
class Shape 
{ 
public: 
    virtual void draw(){} 
}; 
 
class Circle : public Shape 
{ 
public: 
    void draw() 
    { 
        cout << "draw circle" << endl; 
    } 
}; 
 
class Rectangle : public Shape 
{ 
public: 
    void draw() 
    { 
        cout << "draw Rectangle" << endl; 
    } 
}; 
 
class ShapeFactory 
{ 
public: 
    static Shape* create(const char *opt) 
    { 
        if (opt == NULL) 
            return NULL; 
 
        if (!strcmp(opt, "Circle")) 
            return new Circle(); 
        else if (!strcmp(opt, "Rectangle")) 
            return new Rectangle(); 
        else 
            return NULL; 
    } 
}; 
 
int main() 
{ 
    Shape *obj = ShapeFactory::create("Rectangle"); 
     
    if (obj) 
        obj->draw(); 
     
    return 0; 
} 

《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的详细介绍:请点这里
Python 的下载地址:请点这里

本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-10/107869.htm

linux
相关资讯       Python设计模式  Python简单工厂模式 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款