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

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

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

Active Objects (see page 133) provides a native model for handling asynchronicity without the complexity of explicit multi-threadingwhilst providing a convenient class to contain a moderately complexFSM implemented using enumerated constants and a switch statement.This offers an effective compromise between the over-simple and theover-complicated whilst avoiding the drawback of a non-object-orientedC-style approach.StructureWhether the FSM is externally or internally driven, each state representsa single sub-task which starts with an asynchronous request and endswhen it is completed. This is represented by Figure 5.6.The asynchronous controller will have at most three places where thestate it is in makes a difference to its behavior and hence a switchstatement is needed:• Within its RunL() where it uses the state it is in to determinewhich event signal it has received and so what action it should takenext.

Usually this will be a transition to the next state via a private152COOPERATIVE MULTITASKINGfunction that issues the asynchronous request corresponding to thenext sub-task.• If your task needs specific error handling then you should add aRunError() which collects all the error-handling code. A switchmay then be useful to determine which sub-task failed.• You will normally need a switch statement within your DoCancel() to ensure the correct cancellation request is sent for thecurrent sub-task.CActive+ iStatus: TRequestStatusCActiveScheduler1..*+###Cancel()RunL()RunError(Tlnt)DoCancel()CAsychronousControllerMTaskEventMixinCClientFigure 5.6−iObserver: MTaskEventMixin−−WaitingForXxxOneTransition()WaitingForXxxTwoTransition()«enumeration»TStateStructure of the Asynchronous Controller patternDynamicsThe entire task that you wish to achieve is represented by an active objecthence creating the object usually starts the task and destroying it cancelsthe task if it is still running.

Event Mixin (see page 93) is used to providea way for the object that starts the overall task to be told when it hascompleted (see Figure 5.7).The RunL(), RunError() and DoCancel() methods of the asynchronous controller give rise to the dynamic behavior of the FSM andenact the state transitions and actions. Typically the switch statement acts on the enumerated state variable and dispatches a singleaction via a method invocation which should be synchronous and shortrunning.20 If there are further sub-tasks to perform then the switchwill also cause a transition to the next state and issue the associated asynchronous request before waiting to handle the next incomingevent.20 Sinceactive objects are cooperatively multitasked.ASYNCHRONOUS CONTROLLERActive ObjectFrameworkCClientNewL(this)153Service ProviderCAsynchronousControllerWaitingForXxxOneTransition()AsyncRequestOne(iStatus)SetActive()SetState(EWaitingForXxxOne)ProcessRequest()RequestCompleted(iStatus)RunL()WaitingForXxxTwoTransition()AsynRequestTwo()SetActive()SetState(EWaitingForXxxTwo)TaskComplete()At some point later ...Figure 5.7 Dynamics of the Asynchronous Controller patternImplementationYour asynchronous controller will look something like this code:class CMyAsyncController : public CActive{public:static CMyAsyncController* NewL(MTaskEventMixin& aObserver);∼CMyAsyncController();private:CMyAsyncController();void ConstructL();// from CActive154COOPERATIVE MULTITASKINGvoid RunL();TInt RunError(TInt aError);void DoCancel();// State transistionsvoid WaitingForXxxFirstTransition();...void WaitingForXxxLastTransition();private:// Used to signal the completion of the overal taskMTaskEventMixin& iObserver;// For simplicity we show just a single service provider that is used// by each of the sub-tasksRServiceProvider iProvider;// Defined with CMyAsyncController so that the individual enums aren’t// in the global namespaceenum TState{EInitial = 0, // Must be 0 so that it is initialized for us by CBaseEWaitingForXxxFirst,...EWaitingForXxxLast,};TState iState;};This class is then implemented as follows.

Just the ConstructL()function is shown here as the NewL() and the constructor21 are standardfor an active object using two-phase construction.void CAsyncController::ConstructL(){// As an example we assume that all the sub-tasks operate on// the same service and so a handle to it is opened here.User::LeaveIfError(iProvider.Open());// Start the FSMWaitingForXxxFirstTransition();}The state transition functions all follow a similar style so only one isshown here. When creating your specific implementation the contentsof these functions will largely be determined by the exact FSM that yourequire.void CAsyncController::WaitingForXxxFirstTransition(){ASSERT(!IsActive());21Note that you don’t need to set the iState to be EInitial in the constructor sinceCBase classes are zero-initialized when they are created which gives us the correct value.ASYNCHRONOUS CONTROLLER155// Need to set this first in case the async request LeavesiState = EWaitingForXxxFirst;iProvider.AsyncRequest(iStatus);SetActive();}When the above request completes, the RunL() is called and you needto determine exactly which asynchronous request has been completedby switching on iState.

Interestingly, the function is an example whereFail Fast (see page 17) is used (to handle either an illegal or unrecognizedstate in the switch since that indicates a programming fault has occurred)in addition to Escalate Errors (see page 32) (to handle errors from the statetransitions). This works because they are each being used for differenterrors.void CAsyncController::RunL(){// All errors are handled in RunError() so ...User::LeaveIfError(iStatus);switch(iState){case EWaitingForXxxFirst:{// Move on to the next stateWaitingForXxxNextTransition();break;}... // Other states are handled herecase EWaitingForXxxLast:{iObserver->TaskComplete(KErrNone);break;}case EInitial:default:// Illegal or unrecognized statePanic(EUnexpectedAsyncControllerRunlState);break;} // End of switch statement}The RunError() method is used to handle any errors escalated fromthe RunL():TInt CMyActive::RunError(TInt aError){TBool errorResolved = EFalse;switch(iState)156COOPERATIVE MULTITASKING{case EWaitingForXxxFirst:{// For example we can resolve KErrNotFound errors here ...if (aError == KErrNotFound){// Resolve error such as by retryingWaitingForXxxFirstTransition();errorResolved = ETrue;}break;}...

// Other states are handled herecase EInitial:default:// Illegal or unrecognized statePanic(EUnexpectedAsyncControllerRunlState);break;}if (errorResolved){return KErrNone;}// Else the error hasn’t been resolved so end the taskiObserver->TaskComplete(aError);return aError; // Pass the error on up}The DoCancel() method should be used to cancel the asynchronousrequest for the current state. Here we don’t bother sending KErrCancelto the observer since we follow the semantics of CActive::Cancel()which is that this is called when no one cares about the task anymore.void CAsyncController::DoCancel(){switch(iState){case EWaitingForXxxFirst:{iProvider.CancelAsyncRequestOne();break;}... // Other states are handled herecase EInitial:default:// Do nothingbreak;}}ASYNCHRONOUS CONTROLLER157Finally the destructor just calls Cancel() and any resources used arecleaned up:CMyActive::∼CMyActive(){Cancel();// Other cleanup codeiProvider.Close();...}ConsequencesPositives• For a moderate number of sub-tasks (less than ten might be a reasonable rule of thumb) this pattern retains the intuitive simplicity ofa C-style, switch-statement implementation with the added benefitsof encapsulation.• Your thread remains responsive whilst the overall task is being done.For applications, this will mean your UI continues to service end userrequests.• Using Active Objects (see page 133) as part of this pattern gives usall the advantages of that pattern when compared to a multithreadedalternative including the RAM savings, reduced maintenance andtesting costs and the flexibility to prioritize other tasks over the onemanaged by the asynchronous controller.• By wrapping multiple asynchronous requests into a single activeobject, we mitigate one of the disadvantages of Active Objects(see page 133) – that the active scheduler doesn’t scale well to copewith many active objects – by reducing the number of active objectsneeded.Negatives• This pattern doesn’t scale well when the number of sub-tasks increases.• Using Active Objects (see page 133) as part of this pattern gives us allthe disadvantages of that pattern when compared to a multithreadedalternative caused by its cooperative scheduling approach.Example ResolvedHere we just show the how the connection task is resolved.

An asynchronous controller is created to manage the task with a separate statefor both of the asynchronous requests it need to make to the DNS server158COOPERATIVE MULTITASKINGto look up the IP address of the remote device and to establish the TCPconnection to that IP address.The way that the asynchronous controller is started and stopped isslightly different from the pattern described above. For clarity, the taskis not begun in the constructor but instead a separate function has beenadded that begins the connection process – ConnectL(). At the end ofthe task, an additional state has been added to deal with the non-trivialwork that needs to be done once the connection has been made.

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

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

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

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