A simple factory model of Python design patterns

Source: Internet
Author: User
Tags strcmp

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.