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

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

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

This makes the time the enduser waits for the application to initialize less frustrating as they are notleft wondering if they really pressed the launch button. The episodesused by such applications can be roughly categorized as:• Task 1 – React to button press• Creation of the application process and main objects• Show the splash screen (task complete)• Task 2 – Display interactive UI• Create UI controls, etc.• Switch splash screen for the main UI (task complete)• Background operationsThe two tasks are normally run back-to-back using a single serializer.• Loading Protocol Plug-insThe Communications Infrastructure subsystem of Symbian OS usesthis pattern to load different protocol plug-ins at different stages ofdevice start-up.

An episode is used to encapsulate each stage ofdevice start-up and they are implemented using Active Objects (seepage 133) to allow them to asynchronously wait for notification ofthe next state change.5 When notification is received, the episode isresponsible for loading the associated group of protocols.This allows protocols to be loaded in stages so that only thoseprotocols required to show the main device UI are loaded early. Theloading of non-essential or background protocols is deferred until laterin the start-up process after the end user thinks the device has booted.5Distributed by the System Starter using Coordinator (see page 211).306OPTIMIZING EXECUTION TIME• After-Market Application StarterThis component introduced into Symbian OS v9.5 allows applicationsthat have been installed after the device has been created, to registerto be started when the device starts up.

Each application to be startedis represented by an individual episode. Note that this is an examplewhere the pattern is not primarily used to optimize execution timebut rather to allow the order of the list of applications to start to becontrolled dynamically.Variants and Extensions• Long-Running SerializerIf your task takes a long time to complete, then you’ll find that yourthread is less responsive in handling events such those generated bythe end user interacting with your UI. This is because the patternas implemented above synchronously traverses the list of episodesand hence doesn’t provide points where it yields to other tasks beingmultitasked in your thread.If this is a problem then you can solve it by making the serializer a‘long-running active object’ as described in Asynchronous Controller(see page 148) though this will be at the cost of slightly increasedoverhead in terms of both CPU cycles and code size.• Self-Determining Background EpisodeOne way to solve the problem of a client requesting a new task tobe executed before the background episodes from a previous taskhave been completed is for you to encapsulate all the backgroundoperations into a single episode.

When the serializer comes to notifythe client that the task is complete it tells the background episodeto start executing and then passes ownership of the episode to theepisode itself. The serializer is then free to accept the next requestfrom a client for it to perform a task.

The background episode thenexecutes as normal but when it’s done it destroys itself rather thannotifying the serializer.• Dynamic Configuration of EpisodesStoring the individual episodes as an array of pointers to a commoninterface allows the order of the episodes to be easily changed oreven for episodes to be removed. This variant takes this a step furtherto prioritize or eliminate episodes at run time to allow the componentto be easily configured for a particular environment.The optional inclusion of episodes can be accomplished easilywith code similar to the following in the construction of the serializer where the task configuration is read in from an external sourceEPISODES307such as a resource file or the Feature Manager6 service provided bySymbian OS.void CSerializer::ConstructL(){// Read task configurationTTaskConfiguration configuration = ReadTaskConfiguration();// Create the initial episodes// Optionally include the network connection episodeif(configuration.NetworkConnectionRequired()){CNetworkEpisode* ne = CNetworkEpisode::NewLC();iEpisodes.AppendL(ne);CleanupStack::Pop(ne);}}You can also dynamically change the ordering of episodes at run timeas follows:void CSerializer::ConstructL(){// Read task configurationTTaskConfiguration configuration = ReadTaskConfiguration();// Create the initial episodes// Create the cache initialization episodeCCacheEpisode* ce = CCacheEpisode::NewLC();// Optionally add the cache episode as the first episodeif(configuration.InitializeCacheFirst()){iEpisodes.InsertL(ce, 0); // Insert as first episode}else{iEpisodes.AppendL(ce); // Add to the end of the episode list}CleanupStack::Pop(ce);}• Parallelizing EpisodesThe main version of this pattern describes episodes that are startedin sequence.

However, this same design can be extended to allowepisodes to be started in parallel. This is usually done by allowing6 Knownas the Feature Registry in some of the early versions of Symbian OS v9.308OPTIMIZING EXECUTION TIMEeach episode to specify which of the following behaviors should beused when the serializer executes the episode:• Fire and forget – the serializer starts an episode and then immediately moves on to the next in the sequence without waiting fornotification that the episode has finished executing.• Wait – the serializer starts an episode and waits for notificationthat it has finished executing. If all episodes use this behavior thenyou get the same behavior as in the main pattern.• Deferred Wait – the serializer starts an episode and immediatelygoes on to start the next episode.

The serializer will go on startingepisodes until it comes to a synchronization point, often implemented as an episode. The serializer then waits for all deferredwait episodes to finish executing before moving past the synchronization point to the subsequent episode.As you can imagine, these behaviors make the serializer significantlymore complicated as well as making it more difficult to decide uponan optimum way of executing the episodes. However, it does givethe opportunity to further optimize execution time by parallelizing theepisodes.

Of course, this isn’t a guarantee of reducing execution timesince you could waste more time switching context between lots ofdifferent threads if the individual operations of the overall tasks aremainly requests to services across the system.References• Active Objects (see page 133) is used to implement asynchronousepisodes.• Asynchronous Controller (see page 148) can be used to prevent thispattern impacting the responsiveness of your thread.• Coordinator (see page 211) combines well with this pattern by havingan asynchronous episode act as a responder so that it receives notifications of the coordinated state change.

On receiving a notification,it performs the next step in the overall task.DATA PRESS309Data PressIntentQuickly process an incoming stream of data packets, without allocatingany further memory, by using a long-lived object to interpret each packetin turn.AKANone knownProblemContextYou need to efficiently parse a stream of many similar blocks of data,known as packets,7 to route the data stream to its correct destination.Summary• You need to minimize the time between receiving a packet andpassing it on to its destination, which is known as the latency 8 of yourcomponent.• Your component needs to use as little resource, such as RAM, aspossible, irrespective of how much data it processes, to allow theconsumer of the data stream as much freedom to utilize it as possible.• You wish to reduce the power usage of your component as it handleslarge volumes of data.• Your parsing algorithms need to be flexible and easily maintained tocope with future upgrades and improvements.DescriptionData streams are divided up into packets to allow the underlying communication channel to be more easily shared between each of its users.

Thisis because a packet contains a header 9 consisting of control informationsuch as the source and destination addresses, error detection codes suchas checksums, and sequencing information. The rest of the packet isknown as the payload which is the data that the user wishes to send.Processing streams of data formed as a series of packets is a verycommon scenario in a protocol stack that manages the exchange of data7 en.wikipedia.org/wiki/Packet(information technology).en.wikipedia.org/wiki/Latency (engineering).9 Some packets contain a trailer at the end of the packet instead of at the front. However,this doesn’t significantly impact the design so we won’t go into any detail for this variation.8310OPTIMIZING EXECUTION TIMEbetween two devices or across a network and hence this problem ismost commonly seen by device creators.

However, since streaming orfrequent message passing can also occur within a device, or even betweendifferent classes within one process, this problem is also occasionally seenby application developers.In each of these scenarios, there may be several layers of middlewareprotocols that handle the data in transit, with each layer often having todo quite a lot of work in addition to ensuring the data reaches the correctdestination. For instance, it may need to be decrypted or uncompressedbefore being passed on.Still, the most important part of each packet is the payload thatis destined for an application or end user. Middleware should ideallyoperate as transparently as possible, processing each packet quickly andefficiently to leave plenty of CPU and RAM available for processing thepayload when it reaches its destination.

For instance, if the data is ahigh-quality video stream for the end user then the device should focusas much as possible of its resources on displaying that content to the enduser rather than simply downloading it. After all, your parsing algorithmis just a piece of middleware. The interesting data is inside the packetyou are processing and it would be beneficial for this data to be receivedas soon as possible.Sometimes there are strict real-time constraints on the delivery ofstreamed data that make a low-latency parsing algorithm particularlyimportant. Packets carrying voice data need to reach their destinationwithin perhaps 10 or 20 ms to provide a high-quality communicationlink.Another factor to consider is that it’s no good processing the packetsquickly if you drain the battery in doing so.

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

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

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

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