C + + and Factory mode

Source: Internet
Author: User

Original address:

Http://www.cnblogs.com/hebaichuanyeah/p/5459869.html

A factory pattern is defined as a class (factory) that creates an object, which is used to instantiate a specified subclass.

1. Simple Factory mode

example, if there is a code class, Java,c#,c 艹, and so on is the subclass of the class, by Codefactory to instantiate subclasses. and rewrite the virtual function print in the subclass.

Note: In C 艹, if a child class's resource is freed with a pointer from the parent class, and the destructor in the parent class is not a virtual function, then the destructor of the subclass is not called, and the resource of the subclass is not freed, resulting in a memory leak.

#include"iostream"using namespacestd;classcode{ Public: Code () {}; Virtual voidPrintstringstr) =0; Virtual~Code () {};};classCSharp: Publiccode{ Public: CSharp () {}voidPrintstringstr) {cout<<"Console.WriteLine (\ ""<<str<<"\");"<<Endl; }};classCfuck: Publiccode{ Public: Cfuck () {}voidPrintstringstr) {cout<<"cout<< (\ ""<<str<<"\");"<<Endl; }   };classCProgram: Publiccode{ Public: CProgram () {}voidPrintstringstr) {cout<<"printf (\ ""<<str<<"\");"<<Endl; }};classJava: Publiccode{ Public: Java () {}voidPrintstringstr) {cout<<"System.out.printf (\ ""<<str<<"\");"<<Endl; }};classcodefactory{ Public: Code* Createwhatcode (stringname) {        if(Name = ="CSharp")            return NewCSharp (); if(Name = ="Java")            return NewJava (); if(Name = ="CProgram")            return NewCProgram (); if(Name = ="Cfuck")            return NewCfuck ();    }};main () {Codefactory factory; stringprogramname[4]={"CSharp","CProgram","Cfuck","Java"};  for(intI=0;i<4; i++) {Code* Code =Factory.createwhatcode (Programname[i]); Code->print ("Hello World"); DeleteCode; }}

Run results

C + + and Factory mode

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.