python简单工厂模式_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;

}

Python 的详细介绍:请点这里

Python 的下载地址:请点这里

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值