The simple factory pattern is a class-created pattern that is suitable for instantiating a large number of classes with common interfaces, and it can be deferred until run to dynamically determine which class to create, rather than having to know which class to instantiate at compile time.
Python:
#!/usr/bin/env python#-*-coding:utf-8-*-class Circle (object):d EF Draw (self):p rint ' Draw Circle ' class Rectangle ( Object):d EF Draw (self):p rint ' Draw Rectangle ' class Shapefactory (object):d EF 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")) re Turn 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;}
A simple factory model of Python design patterns