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

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

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

This frees them up to be re-used as soonas you have finished with them. The problem with this approach is thatyou might need the resource again almost immediately after you havefinished using it.Consider the situation where a user is using a web browser on theirmobile phone to browse a website. The radio connection to the basestation takes a few seconds to set up (‘allocate’) and then the downloadof the web page is relatively quick.

Once the web page is downloaded,the web browser might immediately tear down (‘de-allocate’) the radioconnection as it is no longer required. However as soon as the enduser clicks on a link in the web page, the radio connection resourcewould need to be allocated again, leading to the end user waiting fora few seconds whilst the connection is re-established. This would havea negative impact on the end user’s experience of the mobile webbrowser.A possible solution to this problem is for the web browser developerto use Immortal (see page 53) and never de-allocate these resources.However, your component would stop being a ‘good citizen’ and preventthese resources from being shared across the system.ExampleSymbian OS contains a system for recognizing file types, such whethera file is a word-processed document or a specific type of audio or videofile. This system is called the recognizers framework and it uses plug-insto supply the code that identifies specific file types.

Since there is a largenumber of different file types there is a corresponding large number ofrecognizer plug-ins.When loaded, recognizers use a significant amount of RAM in additionto taking time to initialize during device start-up so using Immortal (seepage 53) wouldn’t be appropriate.However, the Mayfly strategy would also not be appropriate becauserecognizers tend to be used in quick succession over a short period suchas when a file browser enumerates all the file types in a directory. Hence,using Mayfly would result in file recognition taking longer because therecognizers would be allocated and de-allocated many times.SolutionThis pattern is based on the tactic of the resource client using a Proxy[Gamma et al., 1994] to access the resource and the resource provider,called the lazy de-allocator.

The resource client takes ownership orLAZY DE-ALLOCATION75releases the underlying resource as frequently as is needed11 but itdelegates the management of the actual lifetime of the resource to thelazy de-allocator, which is never de-allocated. This allows the lazyde-allocator to delay the actual de-allocation of the resource.The idea is that when the resource is no longer required by theresource client, indicated by it releasing the resource, then instead of itbeing immediately unloaded it is only unloaded when a specific conditionis met. This is done in the expectation that there is a good chance theresource is going to be needed again soon so we shouldn’t unnecessarilyde-allocate it since we’d just have to allocate it again.This pattern is written from the point of view of immediately allocatinga resource in the expectation that it’ll be needed almost straight away.There are other patterns that can be composed with this one and thatdiscuss allocation strategies so, for simplicity, an Immortal (see page 53)approach is taken to allocation.StructureThe responsibilities of the objects shown in Figure 3.6 are as follows, inaddition to their description in the chapter introduction:• The resource client creates the lazy de-allocator as soon as it iscreated and then uses the PrepareResourceL() and ReleaseResource() functions to indicate when it is using the lazy deallocator as a resource.• The lazy de-allocator provides both the resource provider and resourceinterfaces to the resource client as well as managing the actual lifetimeof the resource by choosing when to de-allocate it.DynamicsFigure 3.7 shows the resource being continually used and never actuallybeing de-allocated by the lazy de-allocator.In Figure 3.8, the resource is used only infrequently and so the lazyde-allocator has decided to de-allocate it so that it can be shared acrossthe system.

The way that the lazy de-allocator works is as follows:• Each time ReleaseResource() is called on the lazy de-allocatorit calls AddDeallocCallback(). This is the point where the lazyde-allocator decides whether or not to create a callback that will fireat some point in the future to de-allocate the resource.11 Usingthe Mayfly approach.76RESOURCE LIFETIMESFigure 3.6 Structure of the Lazy De-allocation pattern• Each time PrepareResourceL() is called on the lazy de-allocatorit calls RemoveDeallocCallback() to prevent the callback fromfiring so that the resource remains allocated.The most important thing that you need to decide when applying this pattern is how to implement the AddDeallocCallback()function as this will be a key factor in determining the trade-offbetween avoiding the execution cost of allocating an object and sharing the resource with the rest of the system. Some common strategiesinclude:• A timer could be used to call DeallocCallback(). This timerwould be started in AddDeallocCallback() and stopped inRemoveDeallocCallback().• If the lazy de-allocator is used as a Proxy for multiple resources of thesame type, then AddDeallocCallback() might simply ensure thatit maintains a constant pool of unowned but allocated resources.

Thisstrategy is very similar to Pooled Allocation [Weir and Noble, 2000].LAZY DE-ALLOCATIONResource ClientLazy De-allocatorResource77Resource ProviderPrepareResourceL()RemoveDeallocCallback()Use()Use()ReleaseResource()AddDeallocCallback()Resource remainsallocated betweenthese two pointsPrepareResourceL()RemoveDeallocCallback()Use()Use()Use()Use()ReleaseResource()AddDeallocCallback()Figure 3.7 Dynamics of the Lazy De-allocation pattern when the resource is in frequent useImplementationSome notes before we get started:• Just to illustrate the code given here a timer has been chosen as thede-allocation strategy.• For simplicity, the lazy de-allocator only handles a single resourcebut it could easily be extended to handle more than one.• For simplicity, error handling is done using Escalate Errors (see page32) although an alternative error-handling strategy could be used.• C classes are used to demonstrate the implementation though it wouldbe possible to use R classes instead with few changes.78RESOURCE LIFETIMESResource ClientLazy De-allocatorInitial :ResourceResource ProviderPrepareResourceL()RemoveDeallocCallback()Use()Use()ReleaseResource()AddDeallocCallback()Fires because theresource client hasn'tre-used the resourcequickly enoughDeallocCallback()Deallocate()destructor()PrepareResourceL()AllocateL()Subsequent:Resourceconstructor()Use()Use()Figure 3.8Dynamics of the Lazy De-allocation pattern when the resource is not in frequent useResourceThe following code simply defines the resource we are using:class CResource : public CBase{public:// Performs some operation and Leaves if an error occursvoid UseL();}LAZY DE-ALLOCATION79Resource ProviderHere is the resource provider:class CResourceProvider : public CBase{public:// Allocates and returns a new CResource object.

If an error occurs,// it Leaves with a standard Symbian error code.static CResource* AllocateL();// Matching De-allocatorstatic void Deallocate(CResource* aResource);};Lazy De-allocatorThis class makes use of the standard Symbian OS CTimer class12 tohandle the de-allocation callback:class CLazyDeallocator: public CTimer{public:CLazyDeallocator* NewL();∼CLazyDeallocator();public: // Resource provider i/f// Ensure a resource is available for use or Leave if that isn’t// possiblevoid PrepareResourceL();// Signal that the client isn’t using the resource any morevoid ReleaseResource();public: // Resource i/fvoid UseL();private:CLazyDeallocator();void ConstructL();// From CActivevoid RunL();TInt RunError(TInt aError);private:CResource* iResource;};The constructor and destructor of this class are straightforward implementations. One point to note is that, to avoid disrupting other more12 Thisis implemented in terms of Active Objects (see page 133).80RESOURCE LIFETIMESimportant tasks, a low priority is given to the timer and hence to whenthe de-allocation callback is run:CLazyDeallocator::CLazyDeallocator(): CTimer(CActive::EPriorityLow){}// Standard two-phase construction – NewL not shown for conciseness.void CLazyDeallocator::ConstructL(){iResource = CResourceProvider::AllocateL();}CLazyDeallocator::∼CLazyDeallocator(){if (iResource){CResourceProvider::Deallocate(iResource);}}The method for retrieving a resource needs to cancel the de-allocationtimer and ensure that a resource is available for later use:CResource* CLazyDeallocator::PrepareResourceL(){Cancel(); // Stops the de-allocation callback// Ensure we have a resource for use laterif (!iResource){iResource = CResourceProvider::AllocateL();}}The following function, ReleaseResource(), simply starts the timerfor the iResource de-allocation callback:const static TInt KDeallocTimeout = 5000000; // 5 secondsvoid CLazyDeallocator::ReleaseResource(){// Check if we’re already active to avoid a stray signal if a client// incorrectly calls this function twice without calling// PrepareResourceL() in betweenif (!IsActive()){After(KDeallocTimeout);}}The value to use for the de-allocation timeout is dependent on thesituation in which you are using this pattern.

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

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

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

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