search
HomeBackend DevelopmentC#.Net TutorialA brief introduction to C++ design patterns and simple factory pattern

Simple factory definition: Implement a factory function to selectively call other operation classes to meet the actual needs of users.

Dividing required functions into multiple components can reduce code coupling and improve code reuse. When the demand for a certain function changes in the future, only partial modifications are needed, so that the entire system is not affected, which greatly improves efficiency.

The object-oriented design idea is to reduce the coupling of the program through encapsulation, inheritance, and polymorphism, while design patterns increase the efficiency of OOP. Proper use of design patterns can make programs more flexible, easy to modify, and reuse.

However, when distinguishing functional components, it is not that the more classes, the better. Classes are divided for encapsulation, but the basis of classification is abstraction. An abstract collection of objects with the same attributes and functions is a class.

Here, we will implement a calculator with addition, subtraction, multiplication and division functions to illustrate the implementation and application of the simple factory pattern.

Test case

[code]int main(){
    //用户输入的两个操作数和一个操作符
    double number1, number2;
    char oper;
    std::cout << "Please enter a binary operation expressions(+-*/):\n";
    std::cin >> number1 >> oper >> number2;
    //声明操作对象
    Operation<double> *operation = new Operation<double>;
    //声明工厂对象
    Factory<double> factory;
    //利用工厂类选择运算符并返回运算对象(加减还是乘或除?)
    operation = factory.createOperate(oper);
    //设置两个操作数.(此处注意operation已经是具体的派生类运算,调用setValue方法是继承自基类的)
    operation->setValue(number1, number2);
    if(operation != NULL){
        //计算结果,此处实际调用的是执行运算的派生类的getResult()方法。即基类指针指向派生类
        double result = operation->getResult();
        std::cout << "Result is: " << result << std::endl;
    }else
        std::cout << "Input is invalid!\n";//输入表达式不合法

    return 0;
}

Class declaration (.h)

[code]//简单工厂模式---实现一个计算器
#ifndef _01SIMPLEFACTORY_H_
#define _01SIMPLEFACTORY_H_
//基类, 运算类模板
template <typename T>
class Operation{
protected:
    //被派生类继承并使用
    T number1, number2;
public:
    //计算结果
    virtual T getResult();
    //设置两个运算值
    void setValue(T , T );  
};

//派生类, 加法类
template <typename T>
class Add: public Operation<T>{
public:
    //具体运算方式, 重写基类的方法
    T getResult()override;  
};

//派生类, 减法类
template <typename T>
class Sub: public Operation<T>{
public:
    //具体运算方式, 重写基类的方法
    T getResult()override;  
};

//派生类, 乘法类
template <typename T>
class Mul: public Operation<T>{
public:
    //具体运算方式, 重写基类的方法
    T getResult()override;  
};

//派生类, 除法类
template <typename T>
class Div: public Operation<T>{
public:
    //具体运算方式, 重写基类的方法
    T getResult()override;  
};

//简单工厂类
template <typename T>
class Factory{
private:
    Operation<T> *operate;
public:
    //根据传入的操作符,创建具体的运算类。返回运算类对象
    Operation<T>* createOperate(const char &op);
};
#endif

Class implementation (.cpp)

[code]#include "01SimpleFactory.h"
#include <iostream>
//类方法实现
template <typename T>
void Operation<T>::setValue(T v1, T v2){//设置两个运算值
    number1 = v1;
    number2 = v2;
}
template <typename T>
T Operation<T>::getResult(){
    return 0;
}
template <typename T>
T Add<T>::getResult(){
    T res = number1 + number2;
    return res;
}
template <typename T>
T Sub<T>::getResult(){
    T res = number1 - number2;
    return res;
}
template <typename T>
T Mul<T>::getResult(){
    T res = number1 * number2;
    return res;
}
template <typename T>
T Div<T>::getResult(){
    double res = 0;
    //0不能作除数,可以作被除数
    if(number2 != 0){
        res = number1 / number2;
        return res;
    }
    std::cout << "0 cannot be used as a divisor\n";
    return 0;
}
//工厂方法,即工厂函数对其他操作类根据功能选择性的调用
template <typename T>
Operation<T>* Factory<T>::createOperate(const char &op){
    switch(op){
    case &#39;+&#39;:
        operate = new Add<T>;
        break;
    case &#39;-&#39;:
        operate = new Sub<T>;
        break;    
    case &#39;*&#39;:
        operate = new Mul<T>;
        break;    
    case &#39;/&#39;:
        operate = new Div<T>;
        break;
    default:
        operate = NULL;
        break;  
    }
    return operate;
}

The above is the implementation of the simple factory pattern.

Summary:

The creational pattern abstracts the instantiation process of a class and can separate the creation of objects from the use of objects.

The simple factory pattern is also called the static factory method pattern, which belongs to the class creation pattern. In the simple factory pattern, instances of different classes can be returned according to different parameters. The simple factory pattern specifically defines a class to be responsible for creating instances of other classes. The created instances usually have a common parent class.

The simple factory pattern contains three roles: the factory role is responsible for implementing the internal logic of creating all instances; the abstract product role is the parent class of all objects created and is responsible for describing the public interface common to all instances; the specific product role is the creation target , all objects created act as instances of a concrete class in this role.

The key point of the simple factory pattern is: when you need something, you only need to pass in a correct parameter to get the object you need without knowing the details of its creation.

The biggest advantage of the simple factory pattern is to separate the creation of objects and the use of objects, and leave the creation of objects to a specialized factory class. However, its biggest disadvantage is that the factory class is not flexible enough. Adding new specific products requires modifying the factory. The judgment logic code of the class, and when there are many products, the factory method code will be very complicated.

The applicable situations of the simple factory pattern include: the factory class is responsible for creating relatively few objects; the client only knows the parameters passed into the factory class and does not care about how to create the objects.

The above is the content of a brief introduction to the simple factory pattern in C++ design patterns. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor