Comparison of simple factory and factory method patterns in C + + design pattern programming _c language

Source: Internet
Author: User
Tags arithmetic

Simple Factory Mode instance
topic: Implement Calculator input 2 number and operator, get result

Engineering Structure:

(1) header file

COperationFactory.h (Operator factory Class)

(2) Source files

SimpleFactory.cpp (client application class, main function)

(3) Operation class

COperation.cpp (OP baseline Class)
COperation.h
COperationAdd.h (addition operator subclass, inherited from Coperation)
COperationDiv.h (division operator subclass, inherited from Coperation)
COperationMul.h (multiplication operator subclass, inherited from Coperation)
COperationSub.h (subtraction operator subclass, inherited from Coperation)

============= Code Implementation Part =============

COperationFactory.h (Operator factory Class)

/************************************************************************//* Operator Factory class * */************************** /#ifndef _operation_factory_h_ #define _operation_factory_h_ Include "stdafx.h" #include "COperation.h" #include "COperationAdd.h" "#include" COperationSub.h "#include" coperationm Ul.h "#include" COperationDiv.h "#include" COperationFactory.h "class Coperationfactory {Public:coperationfact 
  Ory () {}; 
 
  ~coperationfactory () {}; Creates its corresponding operator class pointer, depending on the entry parameters. It's like a factory. Create user-specified operator class pointer static coperation* newoperation (const string& stroperate) {//entry legality judgment to prevent back Stroperate 
    [0] A cross-border access occurs if (Stroperate.size ()!= 1) {return NULL; 
    } coperation* poperation = NULL; 
      Switch (stroperate[0]) {case ' + ': poperation = new Coperationadd (); 
    Break 
      Case '-': poperation = new Coperationsub (); 
    Break Case ' * ': poperation = new CoperatiOnmul (); 
    Break 
      Case '/': poperation = new Coperationdiv (); 
    Break 
    Default:break; 
  return poperation; 
}; 
 
}; 

 #endif _operation_factory_h_


COperation.cpp (OP baseline Class)

#include "stdafx.h" 
#include "COperation.h" 
 
coperation::coperation () 
  : _dnuma (0) 
  , _dnumb (0) 
{ 
 
} 

COperation.h

/************************************************************************// 
* Operation Baseline class * * 
/***************** / 
 
#ifndef _coperation_h_ 
#define _coperation_h_ 
 
class Coperation 
{public 
: 
  coperation (); 
  ~coperation () {}; 
     
  Set op arithmetic 
  void Setnuma (double dnuma) 
  { 
    _dnuma = Dnuma; 
  }; 
   
  Get shipped arithmetic 
  double Getnuma () 
  {return 
    _dnuma; 
  }; 
 
  Set operand 
  void Setnumb (double dnumb) 
  { 
    _dnumb = dnumb; 
 
  Get operands 
  double getnumb () 
  {return 
    _dnumb; 
  }; 
 
  The results are computed and the results are implemented in subclasses. 
  virtual double result () 
  { 
    double dresult = 0; 
    return dresult; 
  } 
 
Private: 
  double _dnuma; 
  Double _dnumb; 
}; 
 
#endif _coperation_h_ 

COperationAdd.h (addition operator subclass, inherited from Coperation)

/************************************************************************// 
* addition operator subclass, inherited from Operation Baseline class * * 
/***** / 
#ifndef _coperation_add_h_ 
#define _coperation_add_h_ 
#include "COperation.h" 
 
 class Coperationadd:public coperation 
 {public 
 : 
   Coperationadd () {}; 
   ~coperationadd () {}; 
 
   Double result () 
   {return      
     (Getnuma () + getnumb ()); 
 
#endif _coperation_add_h_ 

COperationDiv.h (division operator subclass, inherited from Coperation)

/************************************************************************// 
* Division operator subclass, inherited from Op Baseline class/ 
/***** / 
#ifndef _coperation_div_h_ 
#define _coperation_div_h_ 
#include "COperation.h" 
 
class Coperationdiv:public coperation 
{public 
: 
  Coperationdiv () {}; 
  ~coperationdiv () {}; 
 
  Double result () 
  { 
    double dresult = 0; 
    if (0!= getnumb ()) 
    { 
      Dresult = (Getnuma ()/Getnumb ()); 
    } 
    else 
    { 
      cout << "Error:divisor is"; 
    } 
    return dresult; 
  }; 
 
#endif _coperation_div_h_ 

COperationMul.h (multiplication operator subclass, inherited from Coperation)

/************************************************************************// 
* multiplication operator subclass, inherited from Operation Baseline class * * 
/***** / 
#ifndef _coperation_mul_h_ 
#define _coperation_mul_h_ 
#include "COperation.h" 
 
class Coperationmul:public coperation 
{public 
: 
  Coperationmul () {}; 
  ~coperationmul () {}; 
 
  Double result () 
  {return     
    (Getnuma () * GETNUMB ()); 
 
#endif _coperation_mul_h_ 

COperationSub.h (subtraction operator subclass, inherited from Coperation)

/************************************************************************// 
* Subtraction operator subclass, inherited from Operation Baseline class * * 
/***** / 
#ifndef _coperation_sub_h_ 
#define _coperation_sub_h_ 
#include "COperation.h" 
 
class Coperationsub:public coperation 
{public 
: 
  Coperationsub () {}; 
  ~coperationsub () {}; 
 
  Double result () 
  {return     
    (Getnuma ()-getnumb ()); 
 
#endif _coperation_sub_h_ 

SimpleFactory.cpp (client application class, main function)

SimpleFactory.cpp: Defines the entry point for a console application.  
  #include "stdafx.h" #include "COperationFactory.h" int _tmain (int argc, _tchar* argv[]) {//Create an addition operation through an operator factory 
  coperation* Operadd = coperationfactory::newoperation ("+"); if (NULL!= operadd) {Operadd->setnuma (168);//Set Summand Operadd->setnumb (105);//Settings Addends cout 
  ;< << (Operadd->result ()) << Endl; 
  ///Create subtraction operations by operator factory coperation* opersub = coperationfactory::newoperation ("-"); if (NULL!= opersub) {Opersub->setnuma (168);//set to be meiosis Opersub->setnumb (105);//Set meiotic cout 
  ;< "168-105 =" << (Opersub->result ()) << Endl; 
  ///create multiplication operations by operator factory coperation* Opermul = coperationfactory::newoperation ("*"); if (NULL!= opermul) {Opermul->setnuma (168);//set to be multiplier opermul->setnumb (105);//Set multiplier cout 
  ;< << (Opermul->result ()) << Endl; }//ThroughOperator Factory Create division operation coperation* Operdiv = coperationfactory::newoperation ("/"); if (NULL!= operdiv) {Operdiv->setnuma (168);//Set Dividend Operdiv->setnumb (105);//Set divisor cout 
     
    ;< "168/105 =" << (Operdiv->result ()) << Endl;  Operdiv->setnumb (0); 
  Change the divisor cout << (Operdiv->result ()) << Endl; 
  //block console process from ending, easy to see results int nend = 0; 
 
  Cin >> Nend; 
return 0; 

 }

Abstract Factory Pattern Instance

Engineering Structure:

(1) Abstract Product class

IFruit.h

(2) Abstract factory class

IFruitGardener.h

(3) Specific product category

CApple.h

CGrape.h

CStrawberry.h

(4) Specific factory class

CAppleGardener.h

CGrapeGardener.h

CStrawberryGardener.h

(5) Client

FactoryMethodApplication.cpp

(1) Abstract Product class

IFruit.h

/************************************************************************/ 
/* Abstract Fruit Class (abstract Product) * * 
/************************************************************************/ 
#ifndef _ifruit_h_ 
#define _ Ifruit_h_ 
 
#include <string> 
#include <iostream> 
using namespace std; 
 
Class Ifruit 
{public 
: 
  virtual void grow () = 0; 
  virtual void Harvest () = 0; 
  virtual void plant () = 0; 
}; 
 
#endif _ifruit_h_ 

(2) Abstract factory class

IFruitGardener.h

/************************************************************************/ 
/* Abstract Fruit Gardener Class (abstract Factory) * * 
/************************************************************************/ 
#ifndef _ifruit_gardener_h_ 
#define _ifruit_gardener_h_ 
 
#include "IFruit.h" 
 
class Ifruitgardener 
{public 
: 
  virtual ifruit* Factory () = 0; 
}; 
 
#endif _ifruit_gardener_h_ 

(3) Specific product category

CApple.h

/************************************************************************/ 
/* Specific Apple Class (concrete Product) * * 
/************************************************************************/ 
#ifndef _apple_h_ 
# Define _apple_h_ 
 
#include "IFruit.h" 
 
class Capple:public ifruit 
{public 
: 
  void Grow () 
  { 
    cout << "Apple is growing ..." << Endl; 
 
  void Harvest () 
  { 
    cout << "Apple has been harvested." << Endl; 
 
  void Plant () 
  { 
    cout << "Apple has been planted." << Endl; 
 
  int Gettreeage () 
  {return 
    m_iappletreeage; 
  }; 
 
  void settreeage (const int iage) 
  { 
    m_iappletreeage = iage; 
  } 
 
Private: 
  int m_iappletreeage; 
}; 
 
#endif _apple_h_ 

CGrape.h

/************************************************************************/ 
/* Specific grape (concrete Product) * * 
/************************************************************************/ 
#ifndef _grape_h_ 
# Define _grape_h_ 
 
#include "IFruit.h" 
 
class Cgrape:public ifruit 
{public 
: 
  void Grow () 
  { 
    cout << "Grape is growing ..." << Endl; 
 
  void Harvest () 
  { 
    cout << "Grape has been harvested." << Endl; 
 
  void Plant () 
  { 
    cout << "Grape has been planted." << Endl; 
 
  BOOL Getseedless () 
  {return 
    m_bseedless; 
  }; 
 
  void setseedless (const bool bseedless) 
  { 
    m_bseedless = bseedless; 
  }; 
 
Private: 
  bool m_bseedless; 
 
#endif _grape_h_ 

CStrawberry.h

/************************************************************************/ 
/* Specific strawberry category (concrete Product) * * 
/************************************************************************/ 
#ifndef _strawberry_h_ 
#define _strawberry_h_ 
 
#include "IFruit.h" 
 
class Cstrawberry:public ifruit 
{public 
: 
  void Grow ( 
  { 
    cout << "Strawberry is growing ..." << Endl; 
  }; 
 
  void Harvest () 
  { 
    cout << "Strawberry has been harvested." << Endl; 
 
  void Plant () 
  { 
    cout << Strawberry has been planted. "<< Endl; 
 
;}; #endif _strawberry_h_ 

(4) Specific factory class

CAppleGardener.h

/************************************************************************/ 
/* Specific Apple Gardener Class (concrete Factory) * * 
/************************************************************************/ 
#ifndef _apple_gardener_h_ 
#define _apple_gardener_h_ 
 
#include "IFruitGardener.h" 
#include "CApple.h" 
 
class Capplegardener: Public Ifruitgardener 
{public 
: 
  capplegardener (): M_papple (NULL) {}; 
 
  ifruit* Factory () 
  { 
    if (NULL = = m_papple) 
    { 
      m_papple = new Capple (); 
    } 
 
    return m_papple; 
  }; 
 
Private: 
  capple* m_papple; 
 
#endif _apple_gardener_h_ 

CGrapeGardener.h

/************************************************************************/ 
/* Specific Grape Gardener class (Concrete Factory) * * 
/************************************************************************/ 
#ifndef _grape_gardener_h_ 
#define _grape_gardener_h_ 
 
#include "IFruitGardener.h" 
#include "CGrape.h" 
 
class Cgrapegardener: Public Ifruitgardener 
{public 
: 
  cgrapegardener (): M_pgrape (NULL) {}; 
 
  ifruit* Factory () 
  { 
    if (NULL = = M_pgrape) 
    { 
      m_pgrape = new Cgrape (); 
    } 
 
    return m_pgrape; 
  }; 
 
Private: 
  cgrape* m_pgrape; 
 
#endif _grape_gardener_h_ 

CStrawberryGardener.h

/************************************************************************/ 
/* Specific Strawberry Gardener Class (Concrete Factory) * * 
/************************************************************************/ 
#ifndef _strawberry_ Gardener_h_ 
#define _strawberry_gardener_h_ 
 
#include "IFruitGardener.h" 
#include "CStrawberry.h" 
 
Class Cstrawberrygardener:public Ifruitgardener 
{public 
: 
  cstrawberrygardener (): M_pstrawberry (NULL) {}; 
 
  ifruit* Factory () 
  { 
    if (NULL = = M_pstrawberry) 
    { 
      M_pstrawberry = new Cstrawberry (); 
    } 
 
    return m_pstrawberry; 
  }; 
 
Private: 
  cstrawberry* m_pstrawberry; 
 
#endif _strawberry_gardener_h_ 

(5) Client

FactoryMethodApplication.cpp

FactoryMethodApplication.cpp: Defines the entry point for a console application. #include "stdafx.h" #include <Windows.h> #include "IFruitGardener.h" #include "CAppleGardener.h" #include "CGrapeGardener.h" #include "CStrawberryGardener.h" int _tmain (int argc, _tchar* argv[]) {static ifruitgardener* 
  PFruitFactory1 = NULL; 
  static ifruitgardener* PFruitFactory2 = NULL; 
  static ifruit* pFruit1 = NULL; 
 
  static ifruit* pFruit2 = NULL; 
  PFruitFactory1 = new Capplegardener (); 
    if (NULL!= pFruitFactory1) {pFruit1 = Pfruitfactory1->factory (); 
      if (NULL!= pFruit1) {pfruit1->grow (); 
      Pfruit1->harvest (); 
    Pfruit1->plant (); 
  } PFruitFactory2 = new Cgrapegardener (); 
    if (NULL!= pFruitFactory2) {pFruit2 = Pfruitfactory2->factory (); 
      if (NULL!= pFruit2) {pfruit2->grow (); 
      Pfruit2->harvest (); 
    Pfruit2->plant (); 
 
  } sleep (10000); 
return 0; 

 }

Summarize

First of all, both the simple factory model and the factory method model are the unchanged place to extract, the easy to change packaging. To achieve a greater degree of reuse, and adapt to user changes, as well as the expansion of the project.

First, simple factory model

1. Understanding

Also known as a static factory pattern, it specifically defines a class that is responsible for creating instances of other classes, and the instances that are created usually have the same parent class. The factory class dynamically determines which instance of the product class should be created based on the parameters passed in. It contains the necessary judgment logic, can be based on the information given by the outside world, the decision should wear the object of that particular class. Simple factory model can be understood as a father to the son to leave a sum of money, the money can be used to go to school, buy a house or buy a car, and then let his son choose which to use.

2. Advantages

The factory class contains the logical judgments necessary to decide when to create an instance of which class, and the client can avoid creating objects directly. In this way, it can realize the division of responsibility, reduce the coupling, define the specific responsibilities and power, and benefit the optimization of the whole system.

3. Disadvantages

When a product has a more complex multi-layer structure, its factory class is only one, then status quo becomes its biggest disadvantage. Because the factory class is the core of the entire organization, it gathers the creation logic of all products, and once the factory is not working properly, the whole system will be affected and the scalability is poor. If there is a new demand for scalability, you have to modify the factory logic, which will lead to the complexity of the factory logic, violating the open-closed principle. At the same time, static factory method is not conducive to the formation of hierarchical structure based on inheritance.

Second, the factory method mode

1. Understanding

It is a small-grained design pattern, because the performance of the pattern is only an abstract method. The factory method pattern defines an interface for creating objects, allowing subclasses to decide which class to instantiate concretely. That is to add the interface between the factory and the product, the factory is no longer responsible for the implementation of the product, there is an excuse for different conditions to return different class instances, and then by the specific class examples to achieve. Factory methods, the derivation of simple factories, improved the shortcomings of many simple factories, followed the open-closed principle, to achieve scalable, can be used for more complex product results. Factory method can be understood as the same father to the son left a sum of money, and then directly to the son to dominate, how to spend his father regardless.

2. Advantages

Factory approach mode customer service a lot of shortcomings of a simple factory, it each specific factory to complete a single task, and follow the open-closed principle, code concise and has good scalability.

3. Disadvantages

If a product class needs to be modified, the corresponding factory class needs to be modified as well. Once there are multiple product classes that need to be modified, the question of the problem arises, and this is the modification of the factory class becomes quite complicated. Therefore, the factory method model is beneficial to the expansion but is not conducive to maintenance.

To sum up, we can know which mode is more advantageous to programming for different situations. When there are fewer objects to create, the customer knows only the parameters of the incoming factory, does not care about how to create the object, can take a simple factory pattern, and when the class delegates the responsibility of creating the object to one of several helper subclasses, the factory method pattern is used.

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.