I'm trying to implement the Singleton Pattern and Factory Pattern at the same time.
In my mind there can be only one factory for each kind of factory which are based on an abstract class, and use the factory to produce the corresponding shape
object.
But I got an error:
error LNK2001: unresolved external symbol "private: static class TriangleFactory * TriangleFactory::instance" (?instance@TriangleFactory@@0PAV1@A)
I don't know why this happens.Could you tell me how to fix it? The code is as follows.
#include<type_traits>
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<memory>
#include<time.h>
using namespace std;
class Shape
{
public:
virtual void display();
protected:
int x, y;
};
class MyTriangle:public Shape
{
public:
MyTriangle(int _x, int _y)
{
x = _x;
y = _y;
}
MyTriangle()
{
x = rand() % 200;
y = rand() % 200;
}
void display()
{
printf("%d %d\n",x,y);
}
};
class SuperFactory
{
public:
virtual Shape* Execute() = 0;
};
class TriangleFactory :public SuperFactory
{
public:
Shape* Execute()
{
Shape *p = new MyTriangle;
return p;
}
static SuperFactory* GetFactory()
{
return instance;
}
private:
TriangleFactory()
{
instance = nullptr;
instance = new TriangleFactory;
}
~TriangleFactory(){}
static TriangleFactory* instance;
};
int main()
{
MyTriangle *p = dynamic_cast<MyTriangle*>(TriangleFactory::GetFactory()->Execute());
p->display();
return 0;
}
would appreciate your answers :)