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

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

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

For example, if the datato be parsed is in a file, access is mediated at a higher layer by theContacts engine, the Calendar engine or the File Server.• The parser does not need to authenticate its clients directly. Anyauthentication that needs to be done is performed by the service thatmediates access to the secure resource such as the File Server orContacts engine.The parser is used by (at least) the Contacts and Calendar models,the Bluetooth phonebook access profile, and the J2ME implementation.Instead of having the functionality in many places, each requiring itsown maintenance and occupying its own memory, the parser code hasbeen developed once and is maintained in one place.

When the parseris upgraded, all clients get the benefit. The total uncompressed size ofthe parser binaries is around 33 KB, so the ROM savings across just theSymbian OS components which use the parser is around 100 KB.9 Thesestandards are prescribed by the Versit consortium (www.imc.org/pdi.)CLIENT-THREAD SERVICEFigure 6.6177Structure of the Versit Client-Thread ServiceThe services provided by Versit are packaged in three DLLs that areloaded into the client process (see Figure 6.6).

versit.dll exports theservice’s generic base class CVersitParser. This class is extended toprovide specific services for parsing of vCards (exported from vcard.dll) and vCals (exported from vcal.dll) and their sub-entities, suchas vEvents, vTodos, etc. CVersitParser has also been designed sothat it can be extended to parse other data formats with similar requirements.Client ImplementationTo use the vCard service, a client includes the service provider’s headerin a CPP file:#include <vcard.h>Clients can then instantiate the vCard parser service using its NewL()method, internalize the vCard from a stream, and then start doing operations on it:CParserVCard* vCardParser = CParserVCard::NewL();// Create a handle to the input stream, e.g.

from a file ...vCardParser.InternalizeL(stream) // To import a vCardIn the client project’s MMP file, the location of the header file isspecified by a SYSTEMINCLUDE statement and the relevant link librariesare listed in one or more LIBRARY statements:SYSTEMINCLUDE \epoc32\includeLIBRARY vcard.lib versit.lib178PROVIDING SERVICESService Provider ImplementationThe API is typically defined in a header file that is exported to a publicarea via the associated project bld.inf file. The API comprises oneor more classes that are declared as exported10 in a header file. Notethat a class is exported if it has at least one method whose declarationis imported using IMPORT C and whose definition is exported usingEXPORT C.The relevant part of the MMP file for the vCard parser DLL is shownbelow. This is fairly typical – most service providers based on this variantwill be very similar.// VCARD.MMPtargettargettypeCAPABILITYUIDSOURCEPATHuserincludesystemincludesourcelibraryvcard.dllDLLAll -TCB0x1000008D 0x101F4FC6../src../inc/epoc32/includeVCARD.CPPversit.lib euser.libestor.lib bafl.libThe important statement here is TARGETTYPE DLL, which tells thebuild tool chain that it should create a DLL (rather than an EXE orsome other target) and export the required CTS binary interface.

TheLIBRARY statement specifies the statically linked dependencies of thisDLL. For example, vcard.dll links to versit.dll, in order thatCParserVCard can derive from CVersitParser.The CAPABILITY statement specifies the capabilities that this DLL hasbeen granted. A DLL must have at least the capabilities of all of its clientprocesses or they will not be able to load it.11 Device creators usually giveservice DLLs the capabilities ALL – TCB (as above) in order to ensure theservice can be loaded by any process. A third-party developer may notbe able to get the necessary capabilities – in which case they might usean alternative variant (such as supplying the CTS as a static LIB) or allowclients to compile their own versions of the DLL with just the capabilitiesthey need.The other statements are important too, but as they are less relevantto the discussion and are well documented in the Symbian DeveloperLibrary, they are not covered further in this book.

More information,including a detailed architectural overview of Versit, is also given in theSymbian Developer Library.10 Note the word ‘export’ has two meanings here: one refers to header files being exportedfor use during development and the other to classes and functions that are exported froman executable for use at run time.11 See [Shackman, 2006] or [Heath, 2006].CLIENT-THREAD SERVICE179Other Known UsesThis pattern is used in many Symbian OS services and a couple ofexamples are given below. However, it is more common for SymbianOS services to use alternatives to this pattern because they need tomediate access to shared resources.

Often this is not obvious, becausethe service interface supplies a convenience DLL in order to simplifythe inter-process communication. In some cases it’s not obvious thatthere is a shared resource, for example in the case where a service (e.g.cryptographic algorithms) may, on some devices, be implemented inhardware.• EZLib Compression and DecompressionEZLib is a CTS provided by Symbian for compressing and decompressing memory streams, files, and file archives. It is packaged astwo executables, ezlib.dll and ezip.dll, which export a C++interface, CEZCompressor, etc., to the open source executable,libz.dll, which exports a C interface.• DBMSThis pattern is used by DBMS in order to provide a lightweightservice to allow access by a single client to a specific database.

Thisco-exists with a heavier-weight implementation of DBMS based onClient–Server (see page 182), which must be used when a databaseneeds to be accessed by multiple clients or when there are restrictionson which processes may use the database.Variants and Extensions• Dynamically Selected CTSThe Symbian OS ECom service allows a client to select and loada DLL, and hence a CTS, at run time. This gives a client moreflexibility than in the main pattern where the client selects a CTSduring development.

One benefit of this is that the client can copegracefully with a CTS not being available at run time instead of simplyfailing to load.Plug-in selection is done by using the ECom service which isimplemented as a Client–Server (see page 182) and hence involves acontext switch when the plug-in is loaded. However once the EComplug-in has been selected, it acts just as if the DLL providing theplug-in had been loaded directly into the process; thereafter accesshas the same performance benefits as statically loaded DLLs.• Compiling the CTS Directly into Client CodeThis variant incorporates the actual objects in the static LIB into thecalling executable when it is compiled. As a result, every executablethat uses the service contains a copy of the code (see Figure 6.7).180PROVIDING SERVICESFigure 6.7 Structure of the static LIB client-thread serviceThere are few (if any) examples within Symbian OS itself of servicesprovided as static LIBs.

This is because device creation engineersare rarely in the situation where the benefits of using static LIBsoutweigh the costs of the additional code size when compared tousing DLLs. Third-party developers, however, sometimes distributetheir components as static LIBs in order to defer the responsibility forgetting certain Platform Security capabilities to their clients, to removeissues of binary compatibility, and so on.Services based on this variant cannot be upgraded independentlyof the client but, on the other hand, only one copy needs to bemaintained for all clients (no copying and pasting) and there are noissues of binary compatibility between versions.This variant is very responsive. As objects are directly included inthe calling executable there is no thread or process context switch;indeed there isn’t even the, usually very small, start-up cost of loadinga DLL.A further benefit is that since the objects in the LIB are part ofthe calling executable, they do not need to be assigned capabilitiesto be used by its clients.

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

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

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

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