C + + implementation of design patterns 24. Simple Factory mode

Source: Internet
Author: User

The simple factory model, also known as the Static factory model, belongs to the creative model, but is not one of the 23 gof design patterns. A simple factory is an instance of a factory object that determines which product class to create. Simple Factory mode is the simplest and most practical mode in Factory mode, which can be understood as a special implementation of different factory models.

A simple factory determines which product's instance is created by passing in parameters, encapsulates the creation of the object, and the client sees only the abstract object of the product and does not care about the type of the returned subclass.

Simply put, a simple factory is called to pass in a parameter to tell the factory class what kind of object to create, and then the factory class returns the object.

The disadvantage is not to add a product subclass, all to add a Judgment branch in the factory class, which violates the open and closed principle.


Class bass{public:virtual void fun () = 0;bass () {}virtual ~bass () {}};class a:public bass{public:virtual void Fun () {COUT&L t;< "A" <<ENDL;} A () {}virtual ~a () {}};class b:public bass{public:virtual void Fun () {cout<< "B" <<ENDL;} B () {}virtual ~b () {}};class simplefactory{public:simplefactory () {}~simplefactory () {}bass* createproduct (const String type);}; bass* simplefactory::createproduct (const string type) {bass* product = null;if (type = = "a") {Product = new A ();} else if (type = = "B") {Product = new B ();} Else{assert (false);} return product;}


C + + implementation of design patterns 24. Simple 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.