Главная » Просмотр файлов » Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356

Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879), страница 20

Файл №779879 Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (Symbian Books) 20 страницаIssott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879) страница 202018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 20)

One way to do this would be toenable the event generator to make calls directly to the event consumerobject’s member functions. However, this promotes poor encapsulation(the event generator is able to call functions of the event consumer thatare unrelated to event signaling) and tight coupling (the event generatoris hardcoded to generate events for this specific event consumer).ExampleOBject EXchange (OBEX) is a communications protocol that defines ameans for two devices to communicate by passing objects between them.The protocol defines the two ends of an OBEX communication sessionas the OBEX client and the OBEX server.

The OBEX client drives communication by sending requests4 to the OBEX server. The OBEX server isexpected to respond to these requests when it receives them.A single device can support multiple OBEX servers, each offeringa different service to the remote OBEX client such as file transfer or4 Suchas ’get an object’.94EVENT-DRIVEN PROGRAMMINGcontact details transfer.

Each OBEX service requires its own specific logicin addition to the generic OBEX server logic. Hence, to support OBEXservers, a way is needed to separate the generic handling of the OBEXprotocol, forming and parsing packets, from the service-specific logicoffered by the OBEX server in question. The generic logic, as an eventgenerator, would need to be able to send event signals to the servicespecific logic, as an event consumer, when a request from the client isreceived. It is also necessary to allow the generic logic to be bound to anumber of different instances of service-specific logic in order to satisfythe requirement for multiple OBEX services to run on the same device atthe same time.In order to achieve these design goals, one possible solution wouldhave been to use function pointers but this brings with it a host of problemssuch as non-intuitive syntax and code that is difficult to read and debug.SolutionA mixin is an abstract interface that provides a certain functionalityto be inherited by a class.

Classes like this in Symbian OS have theirnames prefixed by an ’M‘ and are known colloquially as M classes.Inheritance of an M class effectively extends the API of the derived classand, through the use of pure virtuals, can force a derived class to providean implementation before it can be instantiated.The main thrust of this pattern is that the developer of the eventgenerator should define an M class, or event mixin, for event consumersto derive from. The event generator then sends event signals by callingfunctions on the event mixin.StructureFigure 4.2 shows how this pattern is structured.

In C++, an M class isimplemented as a class that contains at least one pure virtual function5and no data members. Their lack of member data allows them to beeasily inherited by classes that already inherit from other classes, knownas multiple inheritance, but avoids the problem of a class ending upcontaining multiple copies of a member variable, particularly where aclass inherits from two classes sharing a common subclass.However, with multiple inheritance it is also possible to have morethan one function with the same signature.

This problem is reducedby the following naming convention: prefix the initials of the classname to the name of the function. In Figure 4.2, this is shown bythe MEventMixin function being called MemEventHasOccurredL()rather than EventHasOccurredL().5 Itoften contains just pure virtual functions.EVENT MIXINFigure 4.295Structure of the Event Mixin patternDynamicsBefore any event signals can be propagated, the event generator mustbe provided with a pointer or reference to the event consumer. Howthis occurs depends very much on the relationship between the eventgenerator and event consumer, the relative life spans of the two objects,and the number of event consumers that the event generator can support.A couple of common approaches are listed below:• The event consumer already exists so the event consumer itselfcreates the event generator, passing a reference to itself into the eventgenerator’s factory function.• The event generator already exists so the event consumer calls aregistration function provided by the event generator, passing in areference to itself.Once the event consumer has been registered with the event generator,an event signal can be produced by the event generator calling theappropriate member function of the mixin.

The event consumer thentakes action, before returning program control to the event generator. Apotential problem arises here6 because the event generator is calling theevent consumer synchronously and hence is blocked until the functioncall returns. This means a badly behaved event consumer can break anevent generator. If this is a problem for you, then you can further decouple6 Especially if the event consumer is provided by a different vendor from the eventgenerator.96EVENT-DRIVEN PROGRAMMINGthe two by making the call asynchronous, such as by using Active Objects(see page 133).Finally, when no longer concerned with receiving event signals, theevent consumer may de-register its interest. The means by which it doesthis will usually mirror the means by which the original registration tookplace, for example:• The event consumer is longer lived and hence deletes the eventgenerator.• The event consumer is longer lived and hence calls a deregistrationfunction provided by the event generator, passing in a pointer to itselfas a way of identification.It is a common requirement for event mixin functions to be able tohandle errors since they actually do things that might fail.

This pattern isillustrated using Escalate Errors (see page 32), as indicated by the trailing’L‘ on the event mixin function names, although alternative strategies arepossible.ImplementationThe following code shows a very simple class as an event generator,using an event mixin as the API through which it notifies an event.Event GeneratorTo illustrate this pattern the MEventMixin class given here provides onlyone possible event type, MemEventHasOccurredL(), and providesvery little contextual information on the nature of the event.7 However,you will often find that an event mixin class is used as a means toconvey a number of events and so contains multiple functions which maypass contextual information as parameters to further refine the nature ofevent.class MEventMixin{public:virtual void MemEventHasOccurredL() = 0;};The following is a definition of an event generator.

Note that it isnormally defined at the same time as the MEventMixin class althoughoften in a separate header file so that the event consumer can just includethe M class.7 Henceit is a warm, rather than a hot, event signal.EVENT MIXIN97class MEventMixin; // Forward declareclass CEventGenerator : public CBase{public:void RegisterEventConsumerL(MEventMixin& aEventConsumer);void DeregisterEventConsumerL(MEventMixin& aEventConsumer);private:void ActivityComplete();private:MEventMixin* iRegisteredEventConsumer;};The following implementation allows a single event consumer tobe registered although this could be extended to allow multiple eventconsumers fairly easily.

To protect ourselves from misuse of the APIby clients we should check to see if an event consumer is alreadyregistered:#include "MEventMixin.h"void CEventGenerator::RegisterEventConsumerL(MEventMixin& aEventConsumer){if (iRegisteredEventConsumer){User::Leave(KErrInUse);}iRegisteredEventConsumer = &aEventConsumer;}The following code allows an event consumer to be de-registered.To protect ourselves from misuse of the API by clients, we shouldcheck to see if the event consumer passed in is actually the oneregistered:void CEventGenerator::DeregisterEventConsumerL(MEventMixin&aEventConsumer){// Check the correct event consumer has been passed inif (iRegisteredEventConsumer == &aEventConsumer){iRegisteredEventConsumer = NULL;}else{User::Leave(KErrArgument);}}98EVENT-DRIVEN PROGRAMMINGThe private function is called when the event consumer has anevent signal it wishes to send and shows how the MEventMixin isused:void CEventGenerator::ActivityComplete(){if(iRegisteredEventConsumer){iRegisteredEventConsumer->MemEventHasOccurredL();}}Event generators should take care to deal with the event consumercalling back into the event generator within their implementation ofMemEventHasOccurredL().Event ConsumerThe classes above could then be used by another class acting as an eventconsumer as follows.

We show here an implementation based on anevent generator that exists both before and after the lifetime of the eventgenerator:#include "MEventMixin.h"class CEventGenerator;class CEventConsumer : public CBase, public MEventMixin{public:CEventConsumer* NewL(CEventGenerator& aEventGenerator);∼CEventConsumer();public: // From MEventMixinvoid MemEventHasOccurredL();private:CEventConsumer(CEventGenerator& aEventGenerator);void ConstructL();private:CEventGenerator& iEventGenerator;};Note that the event consumer class has a pointer to the event generatorclass purely to allow it to register itself as an event consumer. Thiscould be removed if the event consumer was registered by some notionalmanagement class owning pointers to both the CEventGenerator andCEventConsumer objects.EVENT MIXIN99Here is the implementation of the event consumer class:#include "CEventGenerator.h"#include "CEventConsumer.h"CEventConsumer::CEventConsumer(CEventGenerator& aEventGenerator):iEventGenerator(aEventGenerator){}The following code shows the event consumer registering with theevent generator immediately although this could be done later if required.Note that the standard NewL() implementation is not shown here forbrevity.void CEventConsumer::ConstructL(){iEventGenerator.RegisterEventConsumerL(*this);}Event consumers must be careful to de-register from the event generatorwhen notifications are no longer needed.

Характеристики

Тип файла
PDF-файл
Размер
2,96 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6264
Авторов
на СтудИзбе
316
Средний доход
с одного платного файла
Обучение Подробнее