interface.h
#include <iostream>
using namespace std;
#ifndef INTERFACE_H__
#define INTERFACE_H__
class IProduct
{
public:
virtual void print() = 0;
};
class IFactory
{
public:
virtual IProduct* create() = 0;
void Deliver(IProduct *pstProduct)
{
if (nullptr == pstProduct)
{
cout << "Invalid product." << endl;
}
pstProduct->print();
}
};
#endif
jacket.h
#include "interface.h"
#ifndef JACKET_H__
#define JACKET_H__
class Jacket:IProduct
{
public:
virtual void print();
};
class JacketFactory:IFactory
{
public:
virtual IProduct* create();
};
void Jacket::print()
{
cout << "This is a jacket." << endl;
}
IProduct* JacketFactory::create()
{
Jacket* pst = new Jacket();
return (IProduct*)pst;
}
#endif
sweater.h
#include "interface.h"
#ifndef SWEATER_H__
#define SWEATER_H__
class Sweater:IProduct
{
public:
virtual void print();
};
class SweaterFactory:IFactory
{
public:
virtual IProduct* create();
};
void Sweater::print()
{
cout << "This is a sweater." << endl;
}
IProduct* SweaterFactory::create()
{
Sweater *pst = new Sweater();
return (IProduct*)pst;
}
#endif
dip.cpp
#include "jacket.h"
#include "sweater.h"
int main()
{
cout << "enter" << endl;
JacketFactory *pstJacketFactory = new JacketFactory();
if (nullptr == pstJacketFactory)
{
cout << "New JacketFactory failed." << endl;
return -1;
}
IProduct* pstJacket = pstJacketFactory->create();
if (nullptr == pstJacket)
{
cout << "Create jacket failed." << endl;
delete pstJacketFactory;
pstJacketFactory = nullptr;
return -1;
}
pstJacket->print();
delete pstJacketFactory;
pstJacketFactory = nullptr;
delete pstJacket;
pstJacket = nullptr;
cout << "exit" << endl;
return 0;
}
执行结果
PS E:\workspace\sample\DIP> g++ dip.cpp
PS E:\workspace\sample\DIP> ./a
enter
This is a jacket.
exit