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

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

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

Bykeeping interfaces decoupled, your solution remains flexible whichmakes future maintenance and evolution easier. Typically, it is mucheasier to update the adapter in the case of future changes than to tryto evolve the clients or the adaptee if that would even be possible.• In the case of a run-time adapter design, new adaptees can beintegrated with potentially no change to the client or even the adapter.This makes your design more open and easily extensible.Negatives• It imposes additional overheads on the use of an adaptee interfacebecause an additional layer is interposed between the client and thefunctionality it wants to use in the adaptee.

This increases both thecode size and the execution time for the solution although they areunlikely to be significant in all but the most extreme of cases.• If you are using this pattern to preserve compatibility by maintaining alegacy API in addition to a new API then this necessarily increases thecomplexity of the system since there are now two APIs for clients tochoose from during development as well as two APIs for the providerof the adapter to support.378MAPPING WELL-KNOWN PATTERNS ONTO SYMBIAN OS• Using a run-time adapter based on the ECom plug-in service has noimpact on execution time once the plug-in has been loaded.

However, searching for and loading a plug-in is an additional overheadcompared to statically loading a DLL which is why, if your intentionis just to wrap a single legacy component, a regular DLL could be abetter choice.Example ResolvedPreserving CompatibilityIn the example described above there was a need to maintain a targetinterface, CCommsDatabase, originally implemented by the CommDBcomponent. However this interface needed to work with the new location for the communications database within the Symbian OS CentralRepository instead of the old DBMS location.

Figure 9.11 shows the oldstructure of CommDB.«interface»CCommsDatabase«implementation»CCommsDatabaseTarget: provides accessto the comms databasewith which we need toretain compatibility.«interface»RDbsDBMS session tothe legacy commsdatabase.Figure 9.11 Legacy structure of CommDBThis problem was solved by removing the old CommDB componentand providing a replacement, the adapter, called the CommDB shimwhich implements the CCommsDatabase interface, the target, in terms ofthe new communications database component CommsDat, the adaptee.This is possible because CommsDat provides all the functionality ofCommDB and more. Figure 9.12 shows the new structure.This solution clearly provides source compatibility between the legacyand the new shim implementations of the CCommsDatabase interfacesince the same class is used in both. Binary compatibility is also preservedby providing the new adapter in a binary with the same name as usedin the legacy solution, commdb.dll.

However, this doesn’t guaranteeADAPTER379Figure 9.12 Structure of the CommDB Adapterthat the new implementation of the old interface will behave exactly as itused to. The only way to guarantee that this behavioral compatibility hasbeen maintained is to ensure the tests written for the legacy CommDBcomponent work for the new shim version.The result of this is that Symbian OS now has two APIs to onecommunications database: CCommsDatabase and CMDBSession.Wrapping Components to Ease PortingThe example described above for this use of the pattern was the portingof SQLite to Symbian OS. The first problem was that, as SQLite isimplemented in standard C, it expects a POSIX API to support it fromunderneath to provide interfaces into the memory model, the file system,and so on.

This was solved by using the PIPS26 to provide near-perfectsupport for the SQLite C calls, requiring little or no tuning of the SQLitecode and working ‘straight out of the box’.More challenging was providing an interface for use by clients ofSQLite. The problem was not that the interface needed to be compatiblewith the legacy database service, DBMS. Instead the existing interface iswritten in C and most Symbian OS programmers would expect a SymbianOS C++ API that supports the system-wide functionality, such as platformsecurity as well as backup and restore. So a new interface for SymbianOS, based on C++ was needed.26 PIPS is POSIX on Symbian (PIPS) is itself a large wrapper for a number of native SymbianOS C++ APIs.380MAPPING WELL-KNOWN PATTERNS ONTO SYMBIAN OSThe key to understanding the final design is to remember that thenew interface to SQLite would have to check the security credentials ofany clients attempting to access a database.

Since this can only be donesecurely across a process boundary,27 this immediately rules out the useof Client-Thread Service (see page 171) to provide the service interface.Instead, Client–Server (see page 182) was selected to be able to providea secure service interface to the underlying SQLite component. Accordingly the new component is called the SQL Server.

This server providesall the support specific to Symbian OS needed by clients accessing theSQLite library underneath. It resulted in the component structure shownin Figure 9.13.Figure 9.13 Structure of the SQLite AdapterRun-time AdaptationAnother example of this pattern is provided by the Symbian OS DeviceManagement (DM) subsystem, which supports all aspects of remote provisioning of devices (for example by network operators) to manage devicesettings. In this case, multiple adapters are required which implement acommon provisioning interface CSmlDmAdapter, the target, which isused by the DM client on the handset acting as an agent for a DM server27 Foran explanation, see the introduction to Chapter 7 in [Heath, 2006].ADAPTER381hosted remotely off the device. The adapters map the common target DMinterface into various settings interfaces provided by diverse Symbian OScomponents, for example phone, messaging, and mail.This gives rise to the structure shown in Figure 9.14.Figure 9.14 Structure of the Device Management AdapterHowever, this only partly solves the design problem.

Some issues stillremain:1. Shielding the client from changes in the adaptee with a binary firewall(not just a compilation firewall)28 to reduce any dependencies duringdevelopment.2. Keeping track of the number of adapters available on the device.3. Loading the appropriate adapter based on the type of settings itsupports.4. Supporting the addition or removal of adapter implementations to orfrom the device at run time to allow third-party developers to supplyadapters for the DM client.Here ECom comes to the rescue. By implementing the adapters asECom plug-ins, the adapters have to be provided in a separate DLLfrom the DM client, thereby making it completely agnostic of theimplementation details or locations of adapters.28This can be achieved to a certain extent with a regular DLL.

However, with DLLs onehas to supply the module definition (DEF) file to be used by the ‘client’ at link time. In thiscase, clearly such a link-time dependency is not suitable.382MAPPING WELL-KNOWN PATTERNS ONTO SYMBIAN OSIssues 2 and 3 are resolved by ECom’s REComSession::ListImplementationsL() and REComSession::CreateImplementationL() methods, which allow the DM client to specify a ‘tag’29that identifies the plug-ins it is looking for.Furthermore, the registry of ECom plug-ins is updated whenevera plug-in is added or removed.

Clients of the ECom service canregister for notification of when this happens, through REComSession::NotifyOnChange(). This is used by the DM Client so thatit can maintain an up-to-date list of adapter implementations availableon the device, which addresses issue 4.This example also illustrates how adapters can potentially handle morethan one adaptee. Going back to the definition of DM, provisioning adevice includes operations such as adding, deleting or modifying variousdevice-level settings. Though there are different types of such settings,each one must support these three main operations. The OMA30 DMprovisioning standard defines these as ADD, DELETE and REPLACE‘commands’ respectively.Consider the case of remotely managing the MMS accounts on adevice.

The MMS framework in Symbian uses two classes to store thedetails of the MMS accounts:• CMmsAccounts is the container for MMS accounts. Each MMSAccount item holds the ID and name of the account along with areference to its MMS Settings object.• CMmsSettings holds all the configuration information that is associated with an MMS account. It includes settings such as proxy and IAPsettings, delivery notification flags, image specifications, and so on.To ‘ADD’ an MMS account, the remote server sends the details viaa SyncML message. The DM framework passes the received details anduses ECom to decide that it should be passed on to the MMS adapter(CDmMmsAdapter). CDmMmsAdapter in turn has to deal with bothCMmsAccounts and CMmsSettings.Figure 9.15 shows a simplified version of how the DM MMS adapterdistributes work to its multiple adaptees.When instructed to create a new MMS account, the CDmMmsAdapterdoes the following:// Create a new MMS Settings objectmmsSettings = CMmsSettings::NewL(); // Adaptee 1CleanupStack::PushL(mmsSettings);29 This ‘tag’ can be anything, ranging from MIME types to number codes.

It is specifiedin the resource (RSS) file of the ECom Plug-in. Custom ECom resolvers can be designedeasily to handle the ‘tag’. Alternatively, the implementation UID of the plug-in can be useddirectly.30 www.openmobilealliance.org .ADAPTER383// Add this to Settings arrayiMmsSettings.AppendL(mmsSettings);// Ownership transferredCleanupStack::Pop(mmsSettings);// Device-management house-keeping code// Create a new MMS accountiMmsAccounts.CreateMMSAccountL(aName, *mmsSettings); // Adaptee 2This is followed by calls to set (or reset) various MMS Settings parameters (as and when the DM commands arrive), e.g.// Set an MMS ProxyiMmsSettings[index].AddProxyL(aProxyUid);or// Set delivery notificationiMmsSettings[index].SetAllowDeliveryNotification(aAllow);Figure 9.15 Dynamics of the Device Management Adapter patternOther Known Uses• Preserving CompatibilityA number of features of Symbian OS may be excluded from adevice by a device manufacturer, usually because it doesn’t have thehardware to support them.

For example, this is true of infrared and384MAPPING WELL-KNOWN PATTERNS ONTO SYMBIAN OSBluetooth. However, if the feature is excluded completely then anyexisting software that uses the feature would fail to compile as theAPIs it depends on aren’t present. Instead a mechanism is providedto allow existing software to compile and instead check at run time ifthe feature is present.This pattern is used to allow such clients to compile by adapting the target interface of a feature to a non-existent adaptee.

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

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

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

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