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

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

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

However, we assume here that all theepisodes are created by the serializer when it is created by the client.This sequence shows the serializer simply traversing through its listof episodes executing them one by one. Once the last required episodehas completed, it notifies the client that the task is done. After the task iscompleted, the background episode is executed.294CClientOPTIMIZING EXECUTION TIMECSerializerrequiredAsync:CAsynchronousEpisoderequiredSync:CSynchronousEpisodebackground:CSynchronousEpisodeDoTask(*this)MeExecute(*this)RunL()MecEpisodeComplete(*this, KErrNone)MeExecute(*this)MecEpisodeComplete(*this, KErrNone)MtcTaskComplete(KErrNone)MeExecute(*this)MecEpisodeComplete(*this, KErrNone)At this point the clientthinks the task iscomplete but the workstill continuesFigure 8.3 Dynamics of the Episodes patternIf an error occurs during the execution of an individual episode, thisshould result in the episode calling MecEpisodeComplete() to passthe error code on to the serializer to handle.

Normally, the serializerwould then halt its progression through the episodes and call MtcTaskComplete() on the client and pass on the error from the episodethat failed. Note that neither of these two completion functions shouldLeave. This is because doing so would pass the error away from theobject that has responsibility for handling the error which is one of theconsequences of using an asynchronous API here.ImplementationBefore getting into further details of how to construct each of the objectsinvolved, you need to decide how to sub-divide the overall task intoepisodes. As a first step you need to identify each of the individualoperations involved and the dependencies between them. This allowsyou to identify which are required before the client can be told the taskhas been completed and which can be done afterwards. You could stopat this point with two episodes however it is often useful to sub-dividethe operations a little more.

The reason for this is that the more episodesyou have, the more flexible and maintainable your component will be infuture since it is relatively easy to re-order episodes or insert new onesEPISODES295whereas moving an operation from one episode to another is usuallymore tricky since closely related operations are normally encapsulatedin the same episode. The downside to having more episodes is that theoverhead of this pattern increases so you need to balance how much youoptimize the task against flexibility for future changes.SerializerThe serializer would be defined as follows:class MEpisodeCompletion{public:virtual void MecEpisodeComplete(MEpisode& aEpisode, TInt aError) = 0;};class CSerializer : public CBase, public MEpisodeCompletion{public:CSerializer* NewL();void DoTask(MTaskCompletion& aTaskObserver);void CancelTask();// From MEpisodeCompletionvirtual void MecEpisodeComplete(MEpisode& aEpisode, TInt aError);private:CSerializer();void ConstructL();void NotifyTaskComplete(TInt aError);private:MTaskCompletion* iTaskObserver;TInt iFirstBackgroundEpisode;RPointerArray<MEpisode> iEpisodes;TInt iCurrentEpisode;};The CSerializer class contains the following member variables:• iTaskObserver, which allows the task to be completed• iFirstBackgroundEpisode, which specifies when the clientshould be informed the task has been completed• iEpisodes, the array of episodes to execute• iCurrentEpisode, the current index to iEpisodes.Implementations of the most interesting methods in CSerializerfollow.

The first is the ConstructL() method, in which all the episodesare created and added to the iEpisodes array. In this method, youshould order the episodes as necessary to get the task done. The only296OPTIMIZING EXECUTION TIMEother thing you need to do is mark the point at which the client should benotified that the task is done by setting iFirstBackgroundEpisode.void CSerializer::ConstructL(){CRequiredAsyncEpisode* ep1 = CRequiredAsyncEpisode::NewLC();iEpisodes.AppendL(ep1);CleanupStack::Pop(ep1);CRequiredSyncEpisode* ep2 = CRequiredSyncEpisode::NewLC();iEpisodes.AppendL(ep2);CleanupStack::Pop(ep2);// Count is used rather than a hard-coded value so that you don’t have// to remember to change the value if you add more episodes aboveiFirstBackgroundEpisode = iEpisodes.Count();CBackgroundSyncEpisode* ep3 = CBackgroundSyncEpisode::NewLC();iEpisodes.AppendL(ep3);CleanupStack::Pop(ep3);}The following method is used by the client to start the task.

Note thatthis function uses Escalate Errors (see page 32) to resolve errors but itdoesn’t do so using the Leave mechanism. Instead all errors are passedup to the client through the MtcTaskComplete() function so that theclient only has the one error path to deal with.The other important point about this function is that you need to checkwhether or not there is already a task ongoing but this can get quite trickyif the required episodes have already been done since the client wouldbe within its rights to think it could ask for the task to be performed again.If this is the case then you have to decide how to deal with this.

The codebelow deals with it very simply by sending an error to the client but thisisn’t very user friendly! The best way to resolve the situation depends onwhat your background episodes do. For instance, it might be that youcan simply cancel the background task and allow the new request to takeprecedence.

Alternatively, you might need to accept the new task andperform it at the same time as the background episodes from the previoustask by using Active Objects (see page 133) specifically to do those tasksand then dying.void CSerializer::DoTask(MTaskCompletion& aTaskObserver){// Check we’re not already busy with a previous taskif (iTaskObserver){aTaskObserver.MtcTaskComplete(KErrInUse);}EPISODES297// Check to see if the background episodes of the previous task are// still being performedif (iCurrentEpisode < iEpisodes.Count()){aTaskObserver.MtcTaskComplete(KErrInUse); // Or something else ...}else{// Need to remember this for the completion lateriTaskObserver = &aTaskObserver;// Reset the episodes as appropriate// Start at first episodeiCurrentEpisode = 0;iEpisode[iCurrentEpisode]->MeExecute(*this);}}The MecEpisodeComplete() function is where most of the workgoes on by dealing with one episode completing and then going on to thenext if there is one:void CSerializer::MecEpisodeComplete(MEpisode& aEpisode, TInt aError){ASSERT(aEpisode == iEpisode[iCurrentEpisode]);if(aError){// Handle the error from a failed episode by passing it to// the client to resolveNotifyTaskComplete(aError);return;}// Move to next episode++iCurrentEpisode;if(iCurrentEpisode == iFirstBackgroundEpisode){// Finished executing the required episodes so signal success// to the clientNotifyTaskComplete(KErrNone);}if (iCurrentEpisode < iEpisodes.Count()){// Execute the next episodeiEpisode[iCurrentEpisode]->MeExecute(*this);}}The NotifyTaskComplete() function just helps ensure that wemaintain the following class invariant: that iTaskObserver is not NULL298OPTIMIZING EXECUTION TIMEonly when the required episodes of a task are being executed:void CSerializer::NotifyTaskComplete(TInt aError){iTaskObserver->MtcTaskComplete(aError);iTaskObserver = NULL;}In the following code, we implement the function to cancel the task.Note that it doesn’t really make sense to allow a client to cancel thebackground episodes since it shouldn’t even be aware that they’re beingexecuted.

Hence we should only act on the cancel if the required episodesare still being executed.void CSerializer::CancelTask(){// Check we’ve been called with a task actually ongoingif (iTaskObserver){iEpisode[iCurrentEpisode]->MeExecuteCancel();}}EpisodesAll episodes derive from the following interface that is implemented asan M class:class MEpisode{public:virtual void MeExecute(MEpisodeCompletion& aEpisodeObserver) = 0;virtual void MeExecuteCancel() = 0;};We show the implementation of the required synchronous episode firstbecause it’s easy to understand.

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

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

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

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