Главная » Просмотр файлов » 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), страница 43

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

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

When a responder has responded, itis removed from the list of waiting responders. If this was the last responsethat the coordinator was waiting for then the next layer is notified of thechange.void CCoordinator::McStateChangeComplete(MResponder& aResponder,TInt aError){ASSERT(iController); // Check a full state change is in progressCOORDINATOR225// Remove the responder from the waiting array. If it can’t be found// then this function has been called incorrectly so panic.TInt index = iWaitingResponders.Find(aResponder);ASSERT(index != KErrNotFound);iWaitingResponders.Remove(index);if(aError < KErrNone && aError != KErrCancel){HandleStateChangeError(aError);return;}// Check to see if waiting for any other responders at this levelif(iWaitingResponders.Count() == 0){// Not waiting for any more responses so notify the next layerNotifyNextLayer();}}When an error occurs whilst handling a state change across all theresponders, the coordinator has the responsibility of canceling any outstanding individual responder state changes and escalating the error tothe controller to resolve properly.void CCoordinator::HandleStateChangeError(TInt aError){// Cancel all outstanding responder state changesconst TInt count = iWaitingResponders.Count();for (TInt i = count; i >= 0; --i){iWaitingResponders[i]->MrHandleStateChange(&this);}// Check the responders have all responded synchronously to the// cancel.

They should’ve each called McStateChangeComplete(KErrCancel)// by now, which would’ve removed them from iWaitingResponders.ASSERT(iWaitingResponders.Count() == 0);// Finished all notifications so notify the controlleriController->MscStateChangeComplete(aError);iController = NULL;}Finally, a way is needed for the controller to tell the coordinator tocancel the state change of all the responders:void CCoordinator::CancelStateChange(){ASSERT(iController); // Check a full state change is in progressHandleStateChangeError(KErrCancel);}226PROVIDING SERVICESMultiple Processes CoordinatorTo implement this pattern to support responders in different processesrequires the addition of responder proxies in the coordinator processand a coordinator proxy in each responder process (see Figure 6.14).Each proxy then implements the necessary IPC to forward a local callto its other corresponding proxy. Symbian OS provides a number ofmechanisms which you can use to provide the necessary IPC; however,Client–Server (see page 182) is an obvious choice because of the highlevel support it offers and the pre-existing client–server framework thathelps you to implement it quickly.Further details can be found in Client–Server, however the followingpoints should give some guidelines for applying it to this pattern:• The coordinator process should host the server with each of theresponder proxies acting as a server session object.• Each responder process acts as a client with a coordinator proxyacting as the client session object.Using Client–Server also makes it possible for you to perform securitychecks on responders before allowing them to register for state changenotifications.

If this is needed then you should implement these securitychecks within the coordinator process since any security checks executedin the client process can be subverted.26ConsequencesPositives• There is loose coupling between components. By using the coordinator to interface between the controller and the responders there isno longer a dependency between them. This makes it very easy toreplace or remove individual responders without needing to changeany other components, not even the coordinator or the controller.This also allows additional dependencies to be added easily by justregistering another responder at the appropriate layer.• The testing cost is reduced; a natural consequence of the loosecoupling is that it is easy to add test responders.• The power usage is reduced as a natural result of the extensive use ofevent-driven programming techniques27 rather than polling for statechanges.• It is easy to change the order in which responders are notified,especially when compared to other potential solutions in which there26 See27 SeeChapter 7 for more information.Chapter 4 for more information.COORDINATOR227are long chains or trees of components passing on the state changenotifications.• This pattern increases robustness as it has a central error-handlingfacility within MStateChanger::MscStateChangeComplete()which allows for a consistent policy for resolving errors.

In addition,the use of this pattern makes the pre-existing dependencies betweencomponents visible and hence they are less likely to be accidentallyignored.• Responsiveness to state changes is increased. The layering specifiedat run time by the responders allows for as much parallelization ofnotifications as is possible without breaking the system.Negatives• It is difficult to change the coordination model since each componentdepends on it.

Any changes after development are likely to affectall the components involved in this pattern and hence could bepotentially quite costly to do if the coordination model is not suitablyfuture proofed.• Error handling is less flexible. Separating the controller from eachof the responders does have the disadvantage of making the errorhandling in the controller necessarily generic and unable to react toerrors with specific responders. This can be partly addressed throughthe Status Reporting extension.• Rollback of a partially complete state change can be difficult if notimpossible.

If a responder fails to transition to the new state partway through the whole state change then there will be respondersin both the new and the old states, which is unacceptable in mostsituations. Depending on your situation this could be resolved byre-trying the state change or even asking responders to reset themselves, however there are a number of situations where this will nothelp.Example ResolvedReturning to the simplified system start-up example, this pattern can beapplied by the system start being the controller. Each application orservice involved in the device start up then has the opportunity to be aresponder.

The coordination model used is as follows:• There are only two possible states: critical boot and non-critical boot.When a responder receives the critical boot state change it shouldonly do the essential operations required to get the phone part ofthe device operational. The non-critical boot state change is used to228PROVIDING SERVICESindicate that components should finish initializing by performing anyremaining initialization operations.28• The Symbian OS system model [Rosenberg and Arshad, 2007]provides a natural layering abstraction.

Using the system model forSymbian OS v9.2 as an example, there are five main layers each ofwhich has up to five sub-layers29 within them. This doesn’t includeapplications so we need to add a new top layer to support them. Thisleads to the following codified coordination model:enum TStartupChanges{ECriticalBoot,ENonCriticalBoot,};enum TSystemLayers{EKernelServices1,EKernelServices2,EKernelServices3,EBaseServices1,EBaseServices2,EBaseServices3,EOsServices1,EOsServices2,EOsServices3,EApplicationServices1,EApplicationServices2,EApplicationServices3,EUiFramework1,EUiFramework2,EUiFramework3,EApplication1,EApplication2,EApplication3,};We still need a coordinator.

It would be possible for the system starteralso to be the coordinator but Symbian OS already has a server whichis suitable for coordinating start-up, called the ‘domain manager’. Thelayers referred to in this pattern are called domains, in the parlance ofthe domain manager. The relationship between these layers is definedby a domain hierarchy. The domain manager is not provided in standardSDKs so is not available to all Symbian OS developers but its RDmDomain(coordinator) and CDmDomain (responder interface) classes are availablefor use by the system starter and responders.28 Responders can use Episodes (see page 289) to help them divide the initialization upinto separate phases.29 For our purposes, just three sub-layers are sufficient.COORDINATOR229The phone application in the example does not need to respond to anyof these changes.

It simply needs to be fully initialized when started, so itwould not be a responder in our example. The remaining components inthe example would be responders with layers assigned as follows:• Communications Infrastructure – EOsServices2• Task scheduling server – EOsServices3• Weather application – EApplication2The ordering of the layers ensures that the communications serverwill have responded to the ENonCriticalBoot change before theweather application is notified, so the protocols required by the weatherapplication will have been loaded by the time it comes to deal with astate change.Dependencies within the same layer are handled using the sub-layers,represented by the numbers at the end of the names. This ensures that thecommunications server (at layer 2 in OS Services) will be notified beforethe task scheduling server (at layer 3 in OS Services).There is a subtlety here when dealing with the ECriticalBoot statechange.

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

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

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

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