JAVA日报
实验6:原型模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解原型模式的动机,掌握该模式的结构;
2、能够利用原型模式解决实际问题。
[实验任务一]:向量的原型
用C++完成数学中向量的封装,其中,用指针和动态申请支持向量长度的改变,使用浅克隆和深克隆复制向量类,比较这两种克隆方式的异同。
实验要求:
1. 画出对应的类图;
2. 提交源代码(用C++完成);
#pragma once
class Prototype
{
public:
Prototype deepclone();
Prototype simpleclone();
};
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#pragma once
class Point
{
public:
double a;
double b;
void setA(double a) {
this->a = a;
}
void setB(double b) {
this->b = b;
}
double getA() {
return this->a;
}
double getB() {
return this->b;
}
};
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#pragma once
#include "Prototype.h"
#include "Point.h"
class Cvector:public Prototype
{
public:
Point *p1=NULL;
Point *p2=NULL;
void setP1(double a, double b) {
p1 = new Point();
(*p1).setA(a);
(*p1).setB(b);
}
void setP2(double a, double b) {
p2 = new Point();
(*p2).setA(a);
(*p2).setB(b);
}
Cvector deepclone() {
Cvector cvector;
cvector.setP1(p1->a, p1->b);
cvector.setP2(p2->a, p2->b);
return cvector;
}
Cvector simpleclone() {
Cvector cvector;
cvector.p1 = p1;
cvector.p2 = p2;
return cvector;
}
};
#include <iostream>
#include "Cvector.h"
int main()
{
Cvector c1;
c1.setP1(1.0, 2.0);
c1.setP2(1.0, 2.0);
Cvector c2;
c2 = c1.simpleclone();
std::cout << "浅克隆:\n";
std::cout << "c1.p1:" << c1.p1 << ":c1.p2" << c1.p2 << "\n";
std::cout << "c2.p1:" << c2.p1 << ":c2.p2" << c2.p2 << "\n";
Cvector c3;
c3 = c1.deepclone();
std::cout << "深克隆:\n";
std::cout << "c1.p1:" << c1.p1 << ":c1.p2" << c1.p2 << "\n";
std::cout << "c3.p1:" << c3.p1 << ":c3.p2" << c3.p2 << "\n";
}