Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
284
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

Chapter 26

// Define the static map.

map<int, vector<const Listener*> > EventRegistry::sListenerMap;

void EventRegistry::registerListener(int inMessage, const Listener* inListener)

{

//Recall from Chapter 21 that indexing into a map adds the element

//with the specified key if it does not already exist. sListenerMap[inMessage].push_back(inListener);

}

void EventRegistry::handleMessage(int inMessage)

{

// Check to see if the message has *any* listeners.

if (sListenerMap.find(inMessage) == sListenerMap.end()) return;

for (int i = 0; i < sListenerMap[inMessage].size(); i++) { sListenerMap[inMessage].at(i)->handleMessage(inMessage);

}

}

Using an Observer

Following is a very simple unit test that demonstrates how to use the publish and subscribe technique. The class TestListener subscribes to message 0 in its constructor. Subscribing to a message in a constructor is a common pattern for objects that are Listeners. The class contains two flags that keep track of whether message 0 was successfully received and whether any unknown messages were received. If message 0 was received and no unknowns were received, the test passes.

class TestListener : public Listener

{

public:

TestListener();

void handleMessage(int inMessage);

bool fMessage0Received;

bool fUnknownMessageReceived;

};

TestListener::TestListener()

{

fMessage0Received = false; fUnknownMessageReceived = false;

// Subscribe to event 0. EventRegistry::registerListener(0, this);

}

void TestListener::handleMessage(int inMessage)

{

switch (inMessage) { case 0:

fMessage0Received = true;

780

Applying Design Patterns

break;

default:

fUnknownMessageReceived = true; break;

}

}

int main(int argc, char** argv)

{

TestListener tl;

EventRegistry::handleMessage(0);

EventRegistry::handleMessage(1);

EventRegistry::handleMessage(2);

if (!tl.fMessage0Received) {

cout << “TEST FAILED: Message 0 was not received” << endl; } else if (tl.fUnknownMessageReceived) {

cout << “TEST FAILED: TestListener received unknown message” << endl; } else {

cout << “TEST PASSED” << endl;

}

}

An actual implementation in your program would vary from the implementation shown based on the services provided by the environment and your individual needs. As you may have noticed, this implementation does not provide a way to unregister a Listener. Unless all objects are guaranteed to stick around forever, they should be unregistered on deletion to avoid bugs. This implementation also allows objects to register twice, which may be undesirable depending on your use case.

Summar y

This chapter has given you just a taste of how patterns can help you organize object-oriented concepts into high-level designs. There is a seemingly infinite supply of design patterns cataloged and discussed on the Portland Pattern Repository Wiki at www.c2.com. It’s easy to get carried away and spend all your time trying to find the specific pattern that applies to your task. We recommend that you focus on a few patterns that interest you and focus your learning on how patterns are developed, not just the small differences between similar ones. After all, to paraphrase the old saying, “Teach me a design pattern, and I’ll code for a day. Teach me how to create design patterns, and I’ll code for a lifetime.”

Design patterns are a terrific way to end your journey through Professional C++ Programming because they are a perfect example of how good C++ programmers can become great C++ programmers. By thinking through your designs, experimenting with different approaches in object-oriented programming, and selectively adding new techniques to your coding repertoire, you’ll be able to take your C++ skills to the Professional level.

781

C++

Inter views

Reading this book will surely give your C++ career a kick-start, but employers will want you to prove yourself before they offer the big bucks. Interview methodologies vary from company to company, but many aspects of technical interviews are predictable. A thorough interviewer will want to test your basic coding skills, your debugging skills, your design and style skills, and your problem solving skills. The set of questions you might be asked is quite large. In this appendix, you’ll read about some of the different types of questions you may encounter and the best tactics for landing that high-paying C++ programming job you’re after.

This appendix iterates through the chapters of the book, discussing the aspects of each chapter that are likely to come up in an interview situation. Each section also includes a discussion of the types of questions that could be designed to test those skills and the best ways to deal with the questions.

Chapter 1: A Crash Course in C++

A technical interview will often include some basic C++ questions to weed out the candidates who put C++ on their resume simply because they’ve heard of the language. These questions might be asked during a phone screen, when a developer or recruiter calls you before bringing you in for an in-person interview. They could also be asked via email or in person. When answering these questions, remember that the interviewer is just trying to establish that you’ve actually learned and used C++. You generally don’t need to get every detail right to earn high marks.

Appendix A

Things to Remember

main() and its parameters

Header file syntax, including the omission of “.h” for standard library headers

Basic use of namespaces

Language basics, such as loop syntax, the ternary operator, and variables

The difference between the stack and the heap

Dynamically allocated arrays

Use of const

Types of Questions

Basic C++ questions will often come in the form of a vocabulary test. The interviewer may ask you to define C++ terms, such as const or static. He or she may simply be looking for the textbook answer, but you can often score extra points by giving sample usage or extra detail. For example, in addition to saying that one of the uses of const is to specify that a reference argument cannot be changed, you can also say that a const reference is more efficient than a copy when passing an object into a function or method.

The other form that basic C++ competency questions can take is a short program that you write in front of the interviewer. An interviewer may give you a warm-up question, such as, “Write Hello, World in C++.” When you get a seemingly simple question like this, make sure that you score all the extra points you can by showing that you are namespace-savvy, you use streams instead of printf(), and you know which standard headers to include.

Chapter 2: Designing Professional

C++ Programs

Your interviewer will want to make sure that in addition to knowing the C++ language, you are skilled at applying it. You may not be asked a design question explicitly, but good interviewers have a variety of techniques to sneak design into other questions, as you’ll see.

Things to Remember

Design is subjective — be prepared to defend design decisions you make during the interview.

Recall the details of a design you’ve done in the past prior to the interview in case you are asked for an example.

Be prepared to define abstraction and give an example.

Be prepared to tout the benefits of code reuse.

Be prepared to sketch out a design visually, including class hierarchies.

784