суббота, 8 февраля 2014 г.

Абстрактная фабрика(Abstract factory)

Позволяет создавать семейство объектов

#include <iostream>
using namespace std;


class Sweetness //product1
{
public:
virtual void print() = 0;
virtual ~Sweetness() {};
};

class Cookie : public Sweetness
{
public:
virtual void print() { cout << "COKKIE!!!" << endl; }
};

class Cake : public Sweetness
{
public:
virtual void print() { cout << "CAKE!!!" << endl; }
};

class Drinks  //product2
{
public:
virtual void print() = 0;
virtual ~Drinks() {}
};

class Tea : public Drinks
{
public:
virtual void print() {cout << "TEA!!!" << endl; }
};

class Coffee : public Drinks
{
public:
virtual void print() {cout << "COFFEE!!!" << endl; }
};

class AbstractFactory
{
public:
virtual Sweetness* getSweetness() = 0;
virtual Drinks* getDrink() = 0;
virtual ~AbstractFactory() {}
};

class TeaAndCookie : public AbstractFactory
{
public:
virtual Sweetness* getSweetness() {return new Cookie; }
virtual Drinks* getDrink() { return new Tea; }
};

class CofeeAndCake : public AbstractFactory
{
public:
virtual Sweetness* getSweetness() {return new Cake; }
virtual Drinks* getDrink() { return new Coffee; }
};

void use(AbstractFactory* ptr)
{
Drinks* drink = ptr->getDrink();
Sweetness* sweet = ptr->getSweetness();

drink->print();
sweet->print();

delete drink;
delete sweet;

cout << endl;
}


int main()
{
AbstractFactory* cookie = new TeaAndCookie;
AbstractFactory* cake = new CofeeAndCake;

use(cookie);
use(cake);

return 0;
}

Комментариев нет:

Отправить комментарий