Читаем 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() {}

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

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

3ds Max 2008
3ds Max 2008

Одни уверены, что нет лучшего способа обучения 3ds Мах, чем прочитать хорошую книгу. Другие склоняются к тому, что эффективнее учиться у преподавателя, который показывает, что и как нужно делать. Данное издание объединяет оба подхода. Его цель – сделать освоение 3ds Мах 2008 максимально быстрым и результативным. Часто после изучения книги у читателя возникают вопросы, почему не получился тот или иной пример. Видеокурс – это гарантия, что такие вопросы не возникнут: ведь автор не только рассказывает, но и показывает, как нужно работать в 3ds Мах.В отличие от большинства интерактивных курсов, где работа в 3ds Мах иллюстрируется на кубиках-шариках, данный видеокурс полностью практический. Все приемы работы с инструментами 3ds Мах 2008 показаны на конкретных примерах, благодаря чему после просмотра курса читатель сможет самостоятельно выполнять даже сложные проекты.

Владимир Антонович Верстак , Владимир Верстак

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