init commit
This commit is contained in:
91
archive/design pattern/factory/factory.cpp
Normal file
91
archive/design pattern/factory/factory.cpp
Normal file
@@ -0,0 +1,91 @@
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
using namespace std;
|
||||
|
||||
class Image
|
||||
{
|
||||
public:
|
||||
virtual void read() = 0;
|
||||
};
|
||||
|
||||
class ImageFactory
|
||||
{
|
||||
public:
|
||||
virtual Image *create() = 0;
|
||||
virtual void read() = 0;
|
||||
};
|
||||
|
||||
class JpgImage : public Image
|
||||
{
|
||||
public:
|
||||
string filename;
|
||||
|
||||
public:
|
||||
JpgImage(string filename)
|
||||
{
|
||||
this->filename = filename;
|
||||
}
|
||||
|
||||
void read()
|
||||
{
|
||||
cout << "读取jpg文件:" << this->filename << endl;
|
||||
}
|
||||
};
|
||||
|
||||
class PngImage : public Image
|
||||
{
|
||||
public:
|
||||
void read()
|
||||
{
|
||||
cout << "读取png图片" << endl;
|
||||
}
|
||||
};
|
||||
|
||||
class JpgImageFactory : public ImageFactory
|
||||
{
|
||||
private:
|
||||
Image *img;
|
||||
|
||||
public:
|
||||
Image *create()
|
||||
{
|
||||
this->img = new JpgImage("file-name");
|
||||
return this->img;
|
||||
}
|
||||
|
||||
void read()
|
||||
{
|
||||
img->read();
|
||||
}
|
||||
};
|
||||
|
||||
class PngImageFactory : public ImageFactory
|
||||
{
|
||||
private:
|
||||
Image *img;
|
||||
|
||||
public:
|
||||
Image *create()
|
||||
{
|
||||
this->img = new PngImage();
|
||||
return this->img;
|
||||
}
|
||||
void read()
|
||||
{
|
||||
img->read();
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
ImageFactory *factory = new JpgImageFactory();
|
||||
Image *img = factory->create();
|
||||
img->read();
|
||||
factory->read();
|
||||
|
||||
factory = new PngImageFactory();
|
||||
img = factory->create();
|
||||
img->read();
|
||||
factory->read();
|
||||
return 0;
|
||||
}
|
Reference in New Issue
Block a user