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

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

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

The challenge here is to reduce the time taken to handle potentiallylarge volumes of data since the main reason there is data to be handledin the first place is because some application has asked for it and wantsto make use of it when it arrives. So we don’t want to be wasting anytime getting the data from place to place; we also want to reduce thepotential for the data handling to fail. This is achieved by pre-allocatingall the memory needed during the parsing of the stream and then usinga long-lived object to interpret each packet of data in turn. This avoidstime-consuming allocations that also introduce unwanted error paths.EPISODES289EpisodesIntentGive the appearance of executing more swiftly by delaying all nonessential operations until after the main task has been completed.AKAStaged Initialization, Phased Initialization, and Staged Start-upProblemContextYou need to perform a significant task on behalf of a client that can bebroken down into a number of separate sequential episodes, only someof which need to be performed immediately.Summary• The client wants the task to appear to be completed as quickly aspossible.• It is important to you to be able to configure how the task is performedeither now or in future.• You want any optimizations to impact the maintainability of yourcomponent as little as possible.DescriptionWhen you perform any non-trivial task, it will be formed of manyindividual parts that need to be completed.

These might vary fromsomething as simple as allocating an in-memory buffer to things ascomplex as checking the integrity of a database. Regardless of whatthese operations are, they each take some period of time to be performed.This applies as much to applications interacting with the end user asto services even though the tasks they perform may differ. For example,an application needs to lay out UI controls on the screen, load imagesor load localized text whilst a service wouldn’t need to do any these.However, the same general problem of a task for which many operations need to be performed is applicable to both situations.

Someof the tasks which are applicable to both applications and servicesare allocation of memory, connecting to a service, requesting information from a service, reading data from disk, verifying data receivedand loading plug-ins. In many cases, the problem is recursive, withan application needing to connect to many servers as part of its task,290OPTIMIZING EXECUTION TIMEeach of which need to perform their own tasks to satisfy the application’s requests.However, the key point is that often not all of the operations performedas part of a task are needed to satisfy the client’s immediate request. Ofcourse, sometimes this is because an operation simply isn’t needed; asan example, consider an end user who views an email for the secondtime, using a messaging application.

If your application goes off to themail server to retrieve the message over the network both times then thesecond retrieval was a waste as the first copy of the message could simplyhave been stored locally. Such operations should be excised entirely andaren’t the focus of this pattern.This pattern focuses on operations which do need to be performed atsome point but not immediately to satisfy the client’s request. Usuallysuch operations are for house-keeping purposes only needed by thecomponent itself.

For example, when removing data from a database,the data is first marked as deleted and then the database is compactedto actually remove it. Only the first operation needs to be performed assoon as possible. Once the data has been marked as deleted, the clientcan carry on while the non-essential compaction operation happensafterwards.Note that this problem applies irrespective of whether the client isinternal to your component or some external client such as the end user.In either case, you want to reduce the time taken to perform the taskthey’ve requested of your component.ExampleTo illustrate this problem, consider the slightly simplified version ofOggPlay [Wilden et al., 2003] discussed here. This media-playing application performs the following high-level operations during its initializationtask:• read any data stored by the end user• load the most recent track list shown to the end user• start playing the last track selected by the end user• construct and display the UI to the end user.The final task effectively signals to the end user that the task of initializing the OggPlay application has completed by switching from its splashscreen to its main screen as shown in Figure 8.1.There are several approaches that we could take to performing theseoperations.

The simplest approach would be to initialize everythingtogether in one method. This would lead to something similar to thefollowing code:EPISODES(a)Figure 8.1291(b)OggPlay screens: a) splash screen b) main application screenvoid COggPlayApplication::ConstructL(){// Load the end user’s dataiUserData = CUserData::NewL();TRequestStatus readingStatus;iUserData->ReadData(readingStatus);User::WaitForRequest(readingStatus); // Wait for completionUser::LeaveIfError(readingStatus.Int());// Load the track listiTrackList = CTrackList::NewL();// Create the main viewiMainView = CMainView::NewL();// Start last track playingiPlayer = CMusicPlayer::NewL();iPlayer->Play();// Initialization done, display main viewiMainView->Display();}The method shown above has the advantages of being straightforwardand containing all the code for the task in one location. This makes iteasier to understand and easy to extend to add any extra operations inthe future by just adding more lines of code to this method.However, after some analysis we realize that some of the operations, such as reading in the end user’s data from disk, take a long292OPTIMIZING EXECUTION TIMEtime.

As a consequence of this, we could decide to encapsulate eachoperation using Active Objects (see page 133) to allow multitasking ofother operations while waiting for file IO to complete. However, sincewe need to perform the operations sequentially this isn’t an optionthat is open to us. The requirement for sequential operations is usually to preserve the dependencies between the operations.

In the codeexample above, playing the last track requires the track list to be loadedfirst.Even if the operations could be parallelized there can be the dangerthat you over-parallelize them. Occasionally the overhead of doing thisactually makes the whole task take longer. For instance, if the individualoperations are requests to services across the system then you can end upin a situation in which more time is wasted context switching betweenlots of different threads than is saved by multitasking.A third approach would be to change each operation so that it isonly done on demand.

For instance, only loading the track list whensome information about the track list is requested.2 This initially mightseem like the ideal option as it allows the application to do the necessaryinitialization just when it’s needed. However, this approach is not withoutits flaws. Firstly, it increases the complexity of your design, especiallyif lots of operations are involved. Secondly, if you know the operationis needed then you may make the responsiveness worse elsewhere.

Inthis case, the end user waits longer than usual when they first try toaccess the track list. Finally, you lose control of the task with the orderingof operations not being decided during development but by run-timechoices and dependencies. This makes debugging any issues significantlymore problematic by making behavior difficult to predict and henceincreasing maintenance and test costs.SolutionThe solution is to encapsulate a group of operations as an episode. As aminimum you need to have a required episode, after which the client istold that their requested task has completed, and a background episodein which the house-keeping tasks can be done in a more relaxed mannerwithout a fixed deadline to meet. You may find that it makes your designor maintenance easier to have more than two episodes.The episodes are then executed sequentially by an object, called herea serializer, to give you predictable behavior.

This allows you to specifythe exact order in which operations need to occur to achieve the task butby encapsulating this you have an easy way to manipulate what episodesoccur during the task. The understanding and control that this gives youallows you to ensure the task is not only done correctly but done asefficiently as possible.2 Furtherdetails of this approach are covered in Lazy Allocation (see page 63).EPISODES293StructureThe client is responsible for starting the whole task by creating theserializer (see Figure 8.2).

The client uses Event Mixin (see page 93) toregister with the serializer for notification of when the task has beencompleted at some point later.Figure 8.2 Structure of the Episodes patternThe serializer is responsible for creating and managing each of theepisodes required for the overall task. It does this by managing a list ofthe episodes which it goes through in order, executing each one fullybefore moving onto the next.

This object uses Event Mixin (see page 93)to register with each episode for notification of when it has completedits work. Note that there must be at least two episodes owned by theserializer since there are, at least, a required and a background episode.Each episode derives from a common interface, MEpisode, so thatthe serializer can be fully decoupled from each of the episodes. Theinterface is designed to allow episodes to execute both synchronouslyand asynchronously. Episodes that you wish to work asynchronouslyshould use Active Objects (see page 133) to achieve this.DynamicsThe dynamics is illustrated in Figure 8.3, which shows three episodes,two required and one background episode. For simplicity, the creationof all the episodes is not shown.

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

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

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

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