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

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

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

a large-mega-pixel camera, if it is an essential selling point for aspecific device) or by regulatory bodies (e.g. the ability to make a callto the emergency services). In all normal situations, an essential serviceshould not fail.4 Hence these services should ensure that all the possibleresources that they need are guaranteed to be available. However, in an4Of course in abnormal situations, for example if the device’s battery is dying, it mightbe reasonable that the essential service does not work.54RESOURCE LIFETIMESopen system such as Symbian OS, resources cannot be guaranteed to beavailable if the allocation is done on demand.

For instance, it might bethat there is not enough memory to allocate all the required objects orthat a communication port is in use by someone else.Alternatively, your problem could be that your software wouldn’t bevery responsive if you took the time to allocate all the resources needed tohandle an event. For instance, you might need to have an open networkconnection through which to send data before you can tell the user theoperation was successful. Having to open the network connection justto send the data each time could ruin the experience for the end user ifdone repeatedly.Lastly, any real-time use case cannot be performed if a resourceallocation within it either takes an unbounded amount of time or simplytakes so long that the required deadlines cannot be met.

One example ofsuch a resource is any memory allocated using the default Symbian OSallocator.Any of these problems might be experienced by any type of SymbianOS developer.ExampleIn many parts of the world, there is a trend to towards ever more accuratelocation information being automatically provided to the emergencyservices when a user makes an emergency phone call on their mobilephone (see, for example, the EU’s Universal Service Directive [EU, 2002]and the USA’s Enhanced 911 – Wireless Services specification [FCC,2001]). To fulfill these, the Symbian OS Location-Based Services (LBS)subsystem must always be able to provide a location for an emergencynetwork location request.

It would not be acceptable to fail to do thisas the result of unsuccessfully allocating a resource in the process ofhandling the request.SolutionAllocate all the immortal resources needed when your application orservice starts but before they are actually needed. Any failure to allocatean immortal resource should result in the entire application or servicefailing to start.StructureBoth the resource and the resource provider are as described in the introduction to this chapter. However, the resource client is also responsiblefor pre-allocating the immortal resource as soon as it is created (seeFigure 3.1).IMMORTALResource Client55Immortal Resourcecache+Use()Resource Provider++Figure 3.1AllocateL()Deallocate()Structure of the Immortal patternDynamicsThe following phases of activity occur at run time (see Figure 3.2):• Construction Phase – when the immortal resource is allocated andheld until it is needed.

Any failure at this stage results in the resourceclient object failing to be constructed (see also Fail Fast on page 17).This phase always happens once, for a particular resource, and occursas soon as the application or service is started to try to avoid contentionwith other potential resource clients.• Usage Phase – when the immortal resource has already been allocatedand can be used without any further initialization. This phase mayoccur multiple times after the Construction Phase.• Destruction Phase – The resource client only de-allocates the immortal resource when the resource client is itself destroyed.ImplementationThe main thing to decide when using this pattern in your design is whatconstitutes an immortal resource and hence needs to be pre-allocated.

Itshould at least meet the following criteria:• It is a resource without which your application can not function.• You are able to fully specify the immortal resources needed duringdevelopment. For instance, you know the total size of RAM or whichcommunication channels are needed and appreciate the impact onthe system due to not sharing these resources.56RESOURCE LIFETIMESResource ClientResource ProviderImmortal Resourceseq Construction PhaseConstructL()AllocateL()Create()seq Usage Phase[Allocation Succeeded]Use ()Use ()seq Destruction Phase[Allocation Succeeded]delete()Deallocate()delete()Figure 3.2Dynamics of the Immortal patternHaving identified the resource, there are a number of ways of implementing the allocation operation depending on the exact type of yourresource. Here are some of the more common methods.Pre-allocation via a C ClassIn this case, one object provides both the resource and the resourceprovider interfaces:IMMORTALclass CResource : public CBase{public:static CResource* NewL(); // Allocator∼CResource();// De-allocatorvoid Use();};class CResourceOwner : public CBase{public:static CResourceOwner* NewL();void DoStuff();private:void ConstructL();private:// When you’re pre-allocating a single object:CResource* iPreAllocatedResource;// When you’re pre-allocating a number of objects:TFixedArray<CResource*, KNumPreAllocatedResources> iPreAllocatedArray;};// All allocation error paths are dealt with upfront during the// construction of the resource client.

If a resource is unavailable// then a Leave will occur.void CResourceOwner::ConstructL(){// Pre-allocation of a single objectiPreAllocatedResource = CResource::NewL();// Pre-allocation of multiple objectsfor (TInt index = 0; index < KNumPreAllocatedResources; index++){iPreAllocatedArray[index] = CResource::NewL();}}// Note the lack of error pathsvoid CResourceOwner::DoStuff(){iPreAllocatedResource->Use();for (TInt index = 0; index < KNumPreAllocatedResources; index++){iPreAllocatedArray[index]->Use();}}5758RESOURCE LIFETIMESCResourceOwner::∼CResourceOwner(){delete iPreAllocatedResource;iPreAllocatedArray.DeleteAll();}For more information on the TFixedArray class, see the SymbianDeveloper Library.In some cases your resource will contain some state within it whichyou don’t want to be persistent across the whole lifetime of the resourceclient.5 To avoid this problem you may need to reset the resource objectbefore using it in the DoStuff() function.

If that is the case then youshould design your resource to have an initialization function separatefrom the constructor. However, you should be careful to ensure that thisfunction doesn’t leave or you’ll have introduced an error path which isexactly what you don’t want.Pre-allocation via an R ClassIn this case, the resource provider acts as a Proxy [Gamma et al., 1994]for the actual resource. Hence the resource client doesn’t actually have apointer directly to the resource itself but accesses it through the resourceprovider:class RResourceProvider{public:TInt OpenL(); // Allocatorvoid Close(); // De-allocatorvoid Use();privateCResource* iResource; // Owned by another class};class CResourceOwner : public CBase{public:static CResourceOwner* NewL(); // Calls ConstructL()void DoStuff();private:void ConstructL();private:RResourceProvider iPreAllocatedResource;};5 Such as the contents of a buffer that isn’t valid between different calls to CResourceOwner::DoStuff().IMMORTAL59// All allocation error paths are dealt with upfront during the// construction of the resource client.

If a resource is unavailable// then a Leave will occur.void CResourceOwner::ConstructL(){iPreAllocatedResource.OpenL();}// Note the lack of error pathsvoid CResourceOwner::DoStuff(){iPreAllocatedResource.Use();}CResourceOwner::∼CResourceOwner(){iPreAllocatedResource.Close();}In this case, RResourceProvider is actually a handle to the realresource somewhere else. For instance, if RResourceProvider werein fact an RSocket being used to hold open a network connectionthen CResourceOwner wouldn’t own any additional memory.

It wouldhowever be responsible for causing the socket server to use moreresources – mainly the communication port but also memory for supporting objects as well as ephemeral resources such as power for theradio antenna to broadcast ’I’m still here‘ signals to the network and CPUcycles to maintain the port in an open state.ConsequencesPositives• You guarantee the resource is available at any point after the Construction Phase. This is often necessary to support critical use cases whereany error occurring due to a failed allocation would be completelyunacceptable.• You control when and how a resource is allocated irrespective of howit is used.• Immortal resources respond more quickly when used since they donot need to be allocated each time.• Using immortal resources reduces the churn in the total set of thatresource type, which can reduce fragmentation.• There is a reduced chance of leaking a resource and so wasting thesystem resources over time since resource de-allocations occur lessfrequently.• Your component is easier to test since its use of the resource ispredictable.60RESOURCE LIFETIMESNegatives• Pre-allocating a resource means that it cannot be used by any otherprocess in the system.

This can be acceptable in closed systemsbut, on an open platform such as Symbian OS, this often causescontention problems between applications and services, especially ifthere aren’t many instances of the immortal resource. Even if the sizeof the immortal resource is small compared to the total amount of theresource, there may still be problems if this pattern is applied acrossthe system many times.• Usability of the device may be reduced because, whilst one component is using a resource, another may not be able to perform itsfunction until that resource has been de-allocated and is free for general use again. This reduces the number of use cases that a device canperform concurrently, which is particularly a problem on high-enddevices.• This pattern can result in waste since the resource usage reflectsthe worst-case scenario.

This is particularly a problem if there arelong periods between each use of the resource or if the resource isnot actually used during the lifetime of the owning application orservice.• Starting applications or services with immortal resources takes longer.• The use of this pattern prevents other lifecycles being used ’underthe hood‘ for individual resources by resource providers on behalf ofresource clients.Example ResolvedAs already mentioned, the LBS subsystem needs to be able to guaranteeto satisfy an emergency network location request. This is true even ifmultiple applications are using the subsystem or if there is no morememory available in the system: a location must still be provided.

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

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

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

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