欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

一,设计模式简介

程序员文章站 2022-06-22 07:50:51
强调了抽象的概念,而不是分而治之,上代码#include #include class Shape{public: virtual void draw() = 0; virtual ~Shape() {}};class Point : public Shape{public: Point() { } ~Point() { } virtual void......

强调了抽象的概念,而不是分而治之,上代码

#include <iostream>
#include <vector>

class Shape
{
public:
    virtual void draw() = 0;
    virtual ~Shape() {}
};

class Point : public Shape
{
public:
    Point()
    {

    }
    ~Point()
    {

    }
    virtual void draw()
    {
        std::cout << "use Point" << std::endl;
    }
};

class Line : public Shape 
{
public:
    Line()
    {
 
    }
    ~Line()
    {

    }

    virtual void draw()
    {
        std::cout << "use line" << std::endl;
    }
};

class Rect : public Shape
{
public:

    Rect()
    {

    }
    ~Rect()
    {

    }

    virtual void draw()
    {
        std::cout << "use Rect" << std::endl;
    }

};

int main()
{
    Shape* ptShape = new Point; 
    Shape* lineShape = new Line;
    Shape* rectShape = new Rect;

    std::vector<Shape*> shapeVector; //这里Shape要用指针,多态性
    shapeVector.push_back(ptShape);
    shapeVector.push_back(lineShape);
    shapeVector.push_back(rectShape);
    for (auto& theShape : shapeVector)  //针对各种形状,各负其责
    {
        theShape->draw();
    }

    
    delete ptShape;
    ptShape = nullptr;
    delete lineShape;
    lineShape = nullptr;
    delete rectShape;
    rectShape = nullptr;

    return 0;
}

 

打印结果是:

use Point
use line
use Rect

 

这里用了抽象类,

如果分而治之,则会需要3个数组,分别判断具体属于哪个类,是点,圆还是线,再调用相应类的方法。如果再添加,还需要再加数组,1万个种类的图形则需要1万种数组

本文地址:https://blog.csdn.net/directx3d_beginner/article/details/107570052

相关标签: 设计模式