设为首页 加入收藏

TOP

Python设计模式 之 简单工厂模式
2014-11-23 19:26:39 来源: 作者: 【 】 浏览:31
Tags: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 None

fac = ShapeFactory()
obj = fac.create('Circle')
obj.draw()


c++:


#include
#include
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;
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C语言头文件组织 下一篇Log4j自定义日志输出

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: