Читаем Thinking In C++. Volume 2: Practical Programming полностью

    for(char** cp = shlist; **cp; cp++)

      shapes.push_back(

        ShapeFactory::createShape(*cp));

  } catch(ShapeFactory::BadShapeCreation e) {

    cout << e.what() << endl;

    return 1;

  }

  for(size_t i = 0; i < shapes.size(); i++) {

    shapes[i]->draw();

    shapes[i]->erase();

  }

  purge(shapes);

} ///:~

Now the Factory Method appears in its own class, ShapeFactory, as the virtual create( ). This is a private member function, which means it cannot be called directly but can be overridden. The subclasses of Shape must each create their own subclasses of ShapeFactory and override the create( ) member function to create an object of their own type. These factories are private, so that they are only accessible from the main Factory Method. This way, all client code must go through the Factory Method in order to create objects.

The actual creation of shapes is performed by calling ShapeFactory::createShape( ), which is a static member function that uses the map in ShapeFactory to find the appropriate factory object based on an identifier that you pass it. The factory is immediately used to create the shape object, but you could imagine a more complex problem in which the appropriate factory object is returned and then used by the caller to create an object in a more sophisticated way. However, it seems that much of the time you don’t need the intricacies of the polymorphic Factory Method, and a single static member function in the base class (as shown in ShapeFactory1.cpp) will work fine.

Notice that the ShapeFactory must be initialized by loading its map with factory objects, which takes place in the Singleton ShapeFactoryInitializer. So to add a new type to this design you must define the type, create a factory, and modify ShapeFactoryInitializer so that an instance of your factory is inserted in the map. This extra complexity again suggests the use of a static Factory Method if you don’t need to create individual factory objects.

<p>Abstract factories</p>

The Abstract Factory pattern looks like the factory objects we’ve seen previously, with not one but several Factory Methods. Each of the Factory Methods creates a different kind of object. The idea is that when you create the factory object, you decide how all the objects created by that factory will be used. The example in Design Patterns implements portability across various graphical user interfaces (GUIs): you create a factory object appropriate to the GUI that you’re working with, and from then on when you ask it for a menu, a button, a slider, and so on, it will automatically create the appropriate version of that item for the GUI. Thus, you’re able to isolate, in one place, the effect of changing from one GUI to another.

As another example, suppose you are creating a general-purpose gaming environment and you want to be able to support different types of games. Here’s how it might look using an Abstract Factory:

//: C10:AbstractFactory.cpp

// A gaming environment

#include

using namespace std;

class Obstacle {

public:

  virtual void action() = 0;

};

class Player {

public:

  virtual void interactWith(Obstacle*) = 0;

};

class Kitty: public Player {

  virtual void interactWith(Obstacle* ob) {

    cout << "Kitty has encountered a ";

    ob->action();

  }

};

class KungFuGuy: public Player {

  virtual void interactWith(Obstacle* ob) {

    cout << "KungFuGuy now battles against a ";

    ob->action();

  }

};

class Puzzle: public Obstacle {

public:

  void action() { cout << "Puzzle\n"; }

};

class NastyWeapon: public Obstacle {

public:

  void action() { cout << "NastyWeapon\n"; }

};

// The abstract factory:

class GameElementFactory {

public:

  virtual Player* makePlayer() = 0;

  virtual Obstacle* makeObstacle() = 0;

};

// Concrete factories:

class KittiesAndPuzzles :

  public GameElementFactory {

public:

  virtual Player* makePlayer() {

    return new Kitty;

  }

  virtual Obstacle* makeObstacle() {

    return new Puzzle;

  }

};

class KillAndDismember :

  public GameElementFactory {

public:

  virtual Player* makePlayer() {

    return new KungFuGuy;

  }

  virtual Obstacle* makeObstacle() {

    return new NastyWeapon;

  }

};

class GameEnvironment {

  GameElementFactory* gef;

  Player* p;

  Obstacle* ob;

public:

  GameEnvironment(GameElementFactory* factory) :

    gef(factory), p(factory->makePlayer()),

    ob(factory->makeObstacle()) {}

  void play() {

    p->interactWith(ob);

  }

  ~GameEnvironment() {

    delete p;

    delete ob;

    delete gef;

  }

};

int main() {

  GameEnvironment

    g1(new KittiesAndPuzzles),

    g2(new KillAndDismember);

  g1.play();

  g2.play();

}

/* Output:

Kitty has encountered a Puzzle

KungFuGuy now battles against a NastyWeapon */ ///:~

Перейти на страницу:

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных