首页 > 代码库 > python设计模式 之 简单工厂模式
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 Nonefac = 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设计模式 之 简单工厂模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。