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

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

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

Theadapter simply provides stubs for the target interface that return KErrNotSupported. This provides a binary- and source-compatible component for clients to use though, of course, it’s not possible to providebehavior compatibility!• PortingJava, Freetype, and OpenGL have all been ported to Symbian OSusing this pattern.• Run-time AdaptersSyncML uses ECom-based adapters to implement an extensible framework for handling multiple transport mechanisms. A number ofTransport Connection Adapters (TCAs) exist for the various transport types (HTTP, OBEX over USB, OBEX over Bluetooth, WSP, etc.)and are implemented as ECom plug-ins. This allows device manufacturers to create new adapter plug-ins to add support for new transportmechanisms.Variants and ExtensionsNone known.References• Buckle (see page 252) should be used when providing run-timeadapters.• Handle–Body (see page 385) also aims to isolate a component’simplementation from the client.

However, the chief intent of aHandle–Body is to allow the client interface and a component implementation to vary independently. Also, this pattern is typically usedto make existing, unrelated classes work together; both parts of Handle–Body are typically introduced together during development toconnect classes which are part of the same design.• Proxy [Gamma et al., 1994], like Adapter, ‘stands in’ for a component. A Proxy, however, provides the same interface as the actualcomponent unlike an Adapter.• Façade [Gamma et al., 1994] ‘wraps’ the complexity of various, oftendissimilar (though logically cohesive), interfaces by combining theminto a unified, easy-to-use interface.HANDLE–BODY385Handle–BodyIntentDecouple an interface from its implementation so that the two can varyindependently.AKACheshire CatProblemContextOne of your components needs to expose an interface for use by externalclients.Summary• You wish your component’s interface to be as encapsulated as possible.• You wish to maintain the compatibility of the exposed interface acrossmultiple versions of your component whilst retaining the freedom tochange how it is implemented.• You would like to rapidly develop a component but also allow foroptimization or the addition of new features later.DescriptionAs the software in mobile devices becomes ever more complicated, italso becomes more difficult to both maintain and extend it.You will often find yourself asking questions such as:• Does my software implement a specification that is subject to changesand updates?• Will I need to allow a different implementation to be provided?• Do I need to cope with different versions of software?• Do I need to develop an early version of a component as soon aspossible which is ’good enough’ now but will need to be re-factoredlater on?The problems of developing software that is easy to expand, maintainand re-factor has and always will be a key issue that you will face.A standard way to achieve this is to ensure your interfaces are wellencapsulated and don’t ‘leak’ any unnecessary details or dependencies386MAPPING WELL-KNOWN PATTERNS ONTO SYMBIAN OSespecially when external clients are relying on the interface to remainstable and not change in any way that will stop them from workingcorrectly.But how can we do this in C++? There are a number of ways toaccidentally break clients.

For instance, you’d think that adding a privatedata member to a class would be safe since it’s private after all. However,doing this increases the size of your class and any client code that calls aclass constructor relies on that being fixed. Indeed one of the benefits ofthe second-phase construction common in Symbian OS31 is that clientsdon’t get to call the constructor directly. Instead they get passed a pointerto the class and hence don’t depend on the size of the class which allowsit to be changed.

Unless it’s an abstract class and clients are expectedto derive from it – then they have to call your class’s constructor whichmakes them sensitive to its size again.Whether you are developing low-level kernel modifications, middlelevel services or end-user applications, the ability to be able to changesoftware quickly and easily will make your life as a developer much lessstressful!ExampleThe HTTP framework provided by Symbian OS supports HTTP requestsand HTTP responses.

A simple design would implement these as twodistinct classes as conceptually they are used for different purposes. Onefactor influencing the design would be that the requests and responsesform part of a well-known protocol that is unlikely to undergo any majorchanges.The framework needed to be developed in an iterative fashion sothat clients had at least some HTTP functionality as soon as possible.Additional features were then added later. For example, the very firstversion of the HTTP framework only supported HTTP GET.

It would takea further nine months and five iterations to fully develop a frameworkwhich had all the required functionality that a web browser requires.Although the two-phase construction idiom used in Symbian OSmeans that the size of the classes could be increased without breakingcompatibility, it was felt that this still exposed too much of the underlyingimplementation details to the clients.

If one mistake was made that meantclients accidentally relied on the details of the implementation ratherthan the interface this would’ve caused serious problems down the line.A way of further separating the implementation of the classes from itsinterface was needed.It was the uncertainty of the future design and the realization that itwould almost certainly need to change that lead to the use of this pattern31 No doubt you’ll have seen this many times as most C classes have a NewL() factoryfunction in Symbian OS. See also [Harrison and Shackman, 2007, Section 4.5].HANDLE–BODY387not just for the request and response classes but across the entire HTTPframework.SolutionThis pattern supports and encourages encapsulation and loose couplingby hiding the implementation details from your clients by dividing oneclass into two. The first of these, the handle, simply defines the interfaceand then defers all implementation of that interface to the body.

One ofthe first descriptions of this was in [Coplien, 1991].A point to remember is that the word ’handle’ being referred to heredoes not necessarily imply the use of a Symbian OS handle derived fromRHandleBase such as RThread or RProcess.StructureA client is only ever able to see the interface class and just uses thatdirectly. However, the interface class delegates all calls through a pointerto the underlying handle which provides the implementation as shown inFigure 9.16.Figure 9.16 Structure of the Handle–Body patternThis particular technique is often referred to in C++ as the ‘CheshireCat Idiom’, named after the character from Lewis Carroll’s Alice inWonderland, and refers to the point where the cat disappears graduallyuntil nothing is left but its smile.

Here the smile is the implementationpointer.If a data member is added to the body class then the size of the handleclass remains the same since its size is just that of a pointer to the body.Hence the client does not need to be recompiled as it is isolated from thischange.The handle and the body classes are normally defined in the same DLLbut only the handle is exported. This binary firewall allows the client to beshielded from any changes in the body. This is particularly advantageousif you would like to vary the details of the implementation depending onthe situation.

For instance, if the interface is used to store and retrieveobjects, the implementation might need to change depending on exactlyhow many objects you expect clients to store. This allows your interfaceto provide the best performance for each situation.388MAPPING WELL-KNOWN PATTERNS ONTO SYMBIAN OSDynamicsThe dynamics of this pattern aren’t very complicated as the handle simplyforwards all calls to its body as shown in Figure 9.17.Figure 9.17 Dynamics of the Handle–Body patternNote that we assume that the body is created at the same time as thehandle which, if we consider the body to be a resource, means Immortal(see page 53) is being used.

This isn’t necessarily the case and otherlifetimes can be chosen for the body as described in Chapter 3.There is one additional subtlety that should be mentioned thoughand that’s the fact that by forcing the body to be allocated on theheap you may have introduced a new error path for the client todeal with. Consider for a moment that you weren’t using this patternand instead provided an exposed interface as a T class used solelyon the client’s stack. Changing the design to use a pointer to a bodyclass instead would mean that clients now also have to deal with thehandle possibly failing to be created which wasn’t a problem previously.ImplementationTo use this pattern you need to separate your interface from your implementation.

If you have an existing class that you wish to convert tousing this pattern then you need to scoop out all the private data members, private functions and implementation of the original class andput them to one side for now. If you add a pointer to a CBody class,HANDLE–BODY389which we’ll define later, then you have the beginnings of your handleclass.You then have the choice of implementing your handle as either an Ror a C class.32 For this illustration, we’ve chosen to use a C class to avoidobscuring the main thrust of the pattern with the additional considerationsthat you need to take into account when using an R class.Next you should forward declare your body class in the header fileused to define your handle class. This avoids you having to #includeany header files for the body and is another means of ensuring theinterface is independent of its implementation.

It also incidentally reducesthe amount of code a client needs to compile when using the interface.This gives the following header file for the handle class:class CBody;class CHandle : public CBase{public:IMPORT_C static CHandle* NewL();IMPORT_C void DoSomethingL();private:CHandle();private:CBody* iBody};The source file for the interface simply has to forward any calls on tothe body.EXPORT_C void CHandle::DoSomethingL(){iBody->DoSomethingL();}Some additional points to note include:• No handle functions should be declared as inline.

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

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

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

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