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

  product->addPart(new BicyclePart(BicyclePart::WHEEL));

}

void RacingBikeBuilder::buildSeat() {

  product->addPart(new BicyclePart(BicyclePart::SEAT));

}

void RacingBikeBuilder::buildDerailleur() {}

void RacingBikeBuilder::buildHandlebar() {

  product->addPart(

    new BicyclePart(BicyclePart::HANDLEBAR));

}

void RacingBikeBuilder::buildSprocket() {

  product->addPart(new BicyclePart(BicyclePart::SPROCKET));

}

void RacingBikeBuilder::buildRack() {}

void RacingBikeBuilder::buildShock() {}

// BicycleTechnician implementation

void BicycleTechnician::construct()

{

  assert(builder);

  builder->createProduct();

  builder->buildFrame();

  builder->buildWheel();

  builder->buildSeat();

  builder->buildDerailleur();

  builder->buildHandlebar();

  builder->buildSprocket();

  builder->buildRack();

  builder->buildShock();

}; ///:~

The Bicycle stream inserter calls the corresponding inserter for each BicyclePart, and that prints its type name so that you can see what a Bicycle contains. The power of this pattern is that it separates the algorithm for assembling parts into a complete product from the parts themselves and allows different algorithms for different products via different implementations of a common interface. Here is a sample program, along with the resulting output, that uses these classes.

//: C10:BuildBicycles.cpp

//{L} Bicycle

#include

#include

#include

#include

#include "../purge.h"

#include "Bicycle.h"

using namespace std;

// Constructs a bike via a concrete builder

Bicycle*

buildMeABike(BicycleTechnician& t, BicycleBuilder* builder) {

  t.setBuilder(builder);

  t.construct();

  Bicycle* b = builder->getProduct();

  cout << "Built a " << builder->getBikeName() << endl;

  return b;

}

int main() {

  // Create an order for some bicycles

  map order;

  order["mountain"] = 2;

  order["touring"] = 1;

  order["racing"] = 3;

  // Build bikes

  vector bikes;

  BicycleBuilder* m = new MountainBikeBuilder;

  BicycleBuilder* t = new TouringBikeBuilder;

  BicycleBuilder* r = new RacingBikeBuilder;

  BicycleTechnician tech;

  map::iterator it = order.begin();

  while (it != order.end()) {

    BicycleBuilder* builder;

    if (it->first == "mountain")

      builder = m;

    else if (it->first == "touring")

      builder = t;

    else if (it->first == "racing")

      builder = r;

    for (size_t i = 0; i < it->second; ++i)

      bikes.push_back(buildMeABike(tech, builder));

    ++it;

  }

  delete m;

  delete t;

  delete r;

  // Display inventory

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

    cout << "Bicycle: " << *bikes[i] << endl;

  purge(bikes);

}

/* Output:

Built a MountainBike

Built a MountainBike

Built a RacingBike

Built a RacingBike

Built a RacingBike

Built a TouringBike

Bicycle: { Frame Wheel Seat Derailleur Handlebar Sprocket Shock }

Bicycle: { Frame Wheel Seat Derailleur Handlebar Sprocket Shock }

Bicycle: { Frame Wheel Seat Handlebar Sprocket }

Bicycle: { Frame Wheel Seat Handlebar Sprocket }

Bicycle: { Frame Wheel Seat Handlebar Sprocket }

Bicycle: { Frame Wheel Seat Derailleur Handlebar Sprocket Rack } */ ///:~

<p>Factories: encapsulating object creation</p>

When you discover that you need to add new types to a system, the most sensible first step is to use polymorphism to create a common interface to those new types. This separates the rest of the code in your system from the knowledge of the specific types that you are adding. New types can be added without disturbing existing code … or so it seems. At first it would appear that you need to change the code in such a design only in the place where you inherit a new type, but this is not quite true. You must still create an object of your new type, and at the point of creation you must specify the exact constructor to use. Thus, if the code that creates objects is distributed throughout your application, you have the same problem when adding new types—you must still chase down all the points of your code where type matters. It happens to be the creation of the type that matters in this case rather than the use of the type (which is taken care of by polymorphism), but the effect is the same: adding a new type can cause problems.

The solution is to force the creation of objects to occur through a common factory rather than to allow the creational code to be spread throughout your system. If all the code in your program must go through this factory whenever it needs to create one of your objects, all you must do when you add a new object is modify the factory. This design is a variation of the pattern commonly known as Factory Method. Since every object-oriented program creates objects, and since it’s likely you will extend your program by adding new types, factories may be the most useful of all design patterns.

As an example, let’s revisit the Shape system. One approach to implementing a factory is to define a static member function in the base class:

//: C10:ShapeFactory1.cpp

#include

#include

#include

#include

#include "../purge.h"

using namespace std;

class Shape {

public:

  virtual void draw() = 0;

  virtual void erase() = 0;

  virtual ~Shape() {}

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

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

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

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

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

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

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

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

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