当前位置: 移动技术网 > 移动技术>移动开发>IOS > 一,设计模式简介

一,设计模式简介

2020年07月27日  | 移动技术网移动技术  | 我要评论

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

#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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网