原型模式

软件设计                  石家庄铁道大学信息学院

 

实验6:原型模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解原型模式的动机,掌握该模式的结构;

2、能够利用原型模式解决实际问题。

 
   

 

 

[实验任务一]:向量的原型

用C++完成数学中向量的封装,其中,用指针和动态申请支持向量长度的改变,使用浅克隆和深克隆复制向量类,比较这两种克隆方式的异同。

实验要求:

1.  画出对应的类图;

 

 

 

2.  提交源代码(用C++完成);

 

#include<cmath>

#include<iostream>

using namespace std;

 

class Vector{

private:

       double *array = new double[4];

       double length;

public:

       Vector(double arr[4])

       {

              this->array[0] = arr[0];

              this->array[1] = arr[1]; 

              this->array[2] = arr[2];

              this->array[3] = arr[3];

              this->length = sqrt(((arr[0] - arr[1])*(arr[0] - arr[1])) + ((arr[2] - arr[3])*(arr[2] - arr[3])));

       }

       ~Vector()

       {

              delete[]array;

              this->length = 0;

       }

       Vector* clone()

       {

              return new Vector(*this);

       }

 

       Vector(const Vector& vector)

       {

              //浅克隆

              this->array = vector.array;

              this->length = vector.length;

 

       }

       void show()

       {

              cout << "向量长度:" << this->length << endl;

       }

};

int main()

{

       double s[4] = { 1, 2, 3, 4 };

       Vector* v1 = new Vector(s);

       Vector* v2 = v1->clone();

       v1->show();

       v2->show();

       return 0;

}

 

 

 

 

 

3.  注意编程规范。

 

posted @ 2021-10-16 19:55  我试试这个昵称好使不  阅读(61)  评论(0编辑  收藏  举报