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

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

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

Simplistic solutions such as copying and pasting do notscale well, because each new copy increases the cost of maintenance. Inaddition, the resources consumed across the system due to the additionalcode size, resulting from all the duplicated code, is unacceptable onconstrained Symbian OS devices.This problem occurs in all software problem domains, ranging fromdevice creation to third-party application development.ExampleCalendar and contacts databases, and indeed any database, usually storetheir data using the most readily available database service – it’s much1 en.wikipedia.org/wiki/Sharedlibrary .172PROVIDING SERVICESfaster to use DBMS (or Symbian SQL from Symbian OS v9.3 onwards)than to invent or port a database engine! In order to exchange contact andcalendar data with personal information management (PIM) applicationson other systems, a common data exchange format and a parser forconverting the data between internal and external formats must exist.A naı̈ve developer might re-write this parser as part of each applicationthat needs it.

This would include at least the PIM UI applications (e.g.Calendar and Contacts) and data synchronization components, such asSyncML. Any third-party software that needs to export PIM entries wouldalso need to have its own parsers.Developing a private version which just does the few things that areinitially required might, at first, appear easier than creating a generic service or understanding a service written by someone else. Unfortunately,each implementation would contribute additional unnecessary code tothe device and hence use more RAM.2 If there was a defect discoveredthen this may or may not also apply to the other instances – certainlythe problem might need to be checked in all of them.

If the underlyingdata-exchange standard was changed, then again the code would needto be updated in each place it was used.SolutionThe solution is to deliver a single copy of what would otherwise beduplicated code as a re-usable client-thread service (CTS). The principalvariant of this pattern is a service hosted in a DLL that is loaded into aclient at run time.This pattern is the default, or preferred, choice for implementing aservice (where it is applicable) because it is the simplest, in terms of implementation, and the most lightweight, in terms of memory consumption.StructureServices based on this pattern run entirely within the client thread.

Forexample, Figure 6.4 shows a CTS packaged in a DLL to which the clientstatically links at compile time.3 To access the CTS, the client.execalls a function exported from the cts.dll. Remember that you shoulddesign services to be extensible, so that they can be updated and extendedwithout affecting clients. In this case, since the CTS is being used via itsexported functions, it is these functions and the associated objects thatyou need to make future-proof.Each process that uses the CTS loads its own copy of the executablecode contained in cts.dll into its virtual address space.4 However, all2 Atleast on a non-XIP device, currently the most common type of Symbian OS device.the code is actually loaded at run time.4 At the time of writing, the most commonly used memory model is the Multiple MemoryModel which only loads executable code into RAM once no matter how many processesload it. See [Sales, 2005] for more information.3 AlthoughCLIENT-THREAD SERVICE173Thread Boundaryclient.exects.dllstaticallylinks toFigure 6.4 Structure of the Client-Thread Service patternof the objects and writable data created using the cts.dll code arelocated on the executing thread’s local heap.5 Hence, each client threadhas its own entirely independent instantiation of the CTS.This structure gives only limited opportunities to enforce securitychecks between the client.exe and the cts.dll.

If this is a requirement for you, see Chapter 7, in particular Buckle (see page 252). However,since this pattern allows clients to operate independently of each other,you at least do not need to worry about one client of the CTS attackinganother client.DynamicsBy the time the client.exe first uses it, the CTS code must havebeen loaded into the client’s process. Usually this is does not take asignificant proportion of time but for large executables (such as those thatare hundreds of KB)6 it might start becoming a factor.7Once the code is loaded the run-time behavior can be as straightforward as a function call from the client to an object, possibly followedby the object returning some value; both cases are shown in Figure 6.5.Of course, more complex scenarios are possible – the service may besupplied by a number of objects, which may make calls to each otherand to other code.ImplementationA CTS is provided through one or more DLLs to which the client staticallylinks at compile time.

To implement this, service providers must exportthe header file, containing the public APIs for the CTS, to the systeminclude directory (\epoc32\include) from their bld.inf file. Clientsaccess the actions of a service by specifying the service header files in5 Assuming you do not use writeable static data (WSD) in DLLs since it costs 4 KB ofRAM per process that uses the CTS. See Singleton (page 346) for further discussion.6 Measured using the urel version of your component compiled for your target hardware.7 Where demand paging is supported, the load time for large executables is significantlyless of an issue.174PROVIDING SERVICESclient.exects.dllRequest1ForService()Request2ForService()ResponseToRequest2()Figure 6.5 Dynamics of the Client-Thread Service patterna #include statement, using the classes they need, and specifying thelinked cts.dll in their MMP file LIBRARY statements.Appropriate platform security capabilities must be specified in theMMP file of the cts.dll.

The service provider should declare all of thecapabilities used by its clients or, if the clients are not known at buildtime, as many capabilities as the signing authority will grant you.8 Notethat this must also include the capabilities required to access the APIsactually called from the cts.dll.

In practice, most developers are notable to get all capabilities (e.g. manufacturer capabilities) so there may bea limit on which clients can use services provided through this pattern.One of the most important parts of specifying a service is the definitionof the service API. The API typically comprises one or more classes. Theexported public interface should be clear and expose as little implementation detail as possible.

When creating the API, you should give someconsideration to how you will provide binary compatibility in the eventof API extension.The Symbian Developer Library includes documentation and examplesfor creating DLLs that you should find useful.ConsequencesPositives• It is simpler for the service provider to implement than almostany other alternative. Only one instance of the code needs to be8 Under the Symbian OS platform security model, a DLL is only trusted to load into aclient process if it has at least the capabilities of that process (the DLL loading rule). Thereforein order to be trusted to be loaded into any client (which may have any capabilities), aservice DLL must have all capabilities (see [Heath, 2006, Section 2.4.5]) although usuallywe settle for All -TCB.CLIENT-THREAD SERVICE175developed, reducing the development time and cost for all its clients.As services are provided in one package, to a large extent the CTScan be maintained, improved and upgraded independently of itsclients.• Services based on this pattern are relatively easy to extend, providedthat thought is put into this when you define the DLL interface.

Ofcourse, care must still be taken to ensure that upgraded servicesmaintain compatibility with previous versions.• It is easy for the client to grow over time: as a CTS often providesmore functionality than is initially used by a single client, it’s notuncommon for it to remain fit for purpose as the client expands itsrole.• Since the service is tested against more users and over a longer timeperiod than stand-alone instances, it is likely to be of high quality.• The variants of this pattern require little ’infrastructure‘ code to implement, thus minimizing the code size.• There is only a single copy of code in physical memory and, typically, there is less code generated in the first place, so less RAM isused.• It is quick to start up.

The start-up time consists almost entirely ofthe cost of loading the service code into memory, which normallydoesn’t take a significant proportion of the time since most DLLs areless than 100 KB on a mobile device. Unlike for other mechanisms,there is no process context switch and little cost in time for the serviceinfrastructure to initialize itself.• The system remains responsive: all functions are accessed from withinthe same thread, so there are no direct costs in switching threador process contexts (there may be indirect costs, for example ifthe service uses other services that are based on different servicepatterns).Negatives• This pattern cannot mediate access to shared resources. It does notinclude mechanisms to provide serial access to a resource, or todeal with concurrency issues such as the atomicity of an operation,because it assumes these issues will never occur.

It is possible to graftsuch support onto this pattern, but the cost of doing so often makesthe use of other patterns a better solution.• The CTS cannot securely verify a client’s identity or its capabilities. Ifyou need to be able to do this then you should consider an alternativepattern, such as Client–Server (see page 182).176PROVIDING SERVICES• Symbian OS is designed to run in a resource-constrained environment.For memory efficiency reasons, the operating system imposes somefurther constraints on the use of this pattern:• Symbian OS uses link-by-ordinal rather than link-by-name, whichrequires additional effort to be taken to maintain binary compatibility.• Symbian OS supports writeable static data (WSD) in DLLs fromSymbian OS v9, but with some cost caveats [Willee, Nov 2007].This is discussed in more detail in Singleton (see page 346) but thecost can be as high as 4 KB per process that uses the CTS. If youare porting a CTS service from operating systems that does makeheavy use of WSD then it may take more development effort tore-design your CTS to avoid the use of WSD than it would to useanother pattern entirely to provide the service.

[Willee, Nov 2007,Section 2.3] discusses this in more detail.Example ResolvedSymbian OS provides a parser for Calendar and Contacts data sharedbetween several applications. The Versit service allows clients to importand export data formatted according to the vCard and vCalendar standards.9 This parser is provided through a client-thread service.This pattern is the obvious choice for the parser design because it’slightweight, simple and well understood. The obvious reasons why thedesign might not be suitable do not apply:• The parser does not need to mediate access to any shared resources.Instead it relies on other services to do this.

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

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

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

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