歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python設計模式 之 簡單工廠模式

Python設計模式 之 簡單工廠模式

日期:2017/3/1 9:38:46   编辑:Linux編程

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 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved