工厂模式!

#include<iostream>
#include <math.h>

#define PI acos(-1)

using namespace std;
//参数相同的构造函数只能定义一次,这时候想要定义点的不同表示怎么办
enum class PointType
{
     cartesian,//直角坐标
     polar//极坐标
};

struct Point
{
    //private 修饰,只能内部调用。
private:
    Point(const float x, const float y) :x(x),y(y){
    }
    
    /*Point(const float r, const float theta) :x(r), y(theta) {
        x = r * cos(theta);
        y = r * sin(theta);
    }*/
    /*Point(const float a, const float b,PointType type=PointType::cartesian) :x(a), y(b) {
        if (type == PointType::cartesian)
             {
                x = a;
                y = b;
             }
        else
            {
            x = a * cos(b);
            y = a * sin(b);
            }
    }*/
//public :
//    static Point NewCartesian(float x, float y)
//         {
//        return { x,y };
//         }
//    static Point NewPolar(float r, float theta) {
//
//        return { r * cos(theta), r * sin(theta) };
//    }
public:
    friend class PointFactory;//友元类,内部类可以访问外部类的私有成员,外部类访问内部类
    float x, y;
};
//工厂类
struct PointFactory
    {
    //工厂方法,属于类的方法
    static Point NewCartesian(float x, float y)
         {
         return Point{ x,y };
        }
     static Point NewPolar(float r, float theta)
         {
         return Point{ r * cos(theta), r * sin(theta) };
        }
 };

void print(Point *b) {
    cout << b->x << endl;
    cout << b->y<<endl;
}

int main() {
    //保护构造函数,外部不可访问
    //Point* a = new Point(3,4);
    //print(a);
    //Point* b = new Point(4,PI/4,PointType::polar);
    //print(b);
    //提高篇1
    /*auto p = Point::NewPolar(4, PI / 4);
    cout << "x:" << p.x<<"y:" << p.y;*/
    //auto * q=new Point(4,3);保护构造函数,外部不可访问
    提高篇2
    auto my_point = PointFactory::NewCartesian(3, 4);
    cout << "x:" << my_point.x << "y:" << my_point.y;
    //工厂模式,只需要告诉工厂自己想要创建什么样的产品,工厂有不同类型的制作方法
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值