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

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

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

Whilst it is temptingto do this as their implementation is so simple, it means you will notbe able to change the function ever again without breaking binarycompatibility. This is because an inline function puts the code for thefunction in the client’s binary33 and not yours, which breaches thebinary firewall that we are trying to erect.32 It can’t be an M class as it has a data member, nor can it be a T class as the data is onthe heap.33Whilst it’s true that sometimes functions marked as inline aren’t actually inlined by thecompiler, it can happen and so we have to treat the functions as if they will actually beinlined to avoid any risk of breaking compatibility.390MAPPING WELL-KNOWN PATTERNS ONTO SYMBIAN OS• The handle class normally does not contain any private functionsexcept for the constructor functions.

Instead all such functions shouldbe implemented by the body class.• Do not implement the body by providing virtual functions in thehandle class and then deriving the body from the handle. Whilst thismakes the implementation of the handle slightly simpler, it effectivelydestroys the benefits of this pattern by exposing the size of the classto further derived classes; introducing vtables which are tricky tomaintain binary compatibility for, and preventing alternative bodiesto be used at run time.• No ConstructL() function is needed as normally you would justcall a function on the body that returns a fully constructed object.ConsequencesPositives• This pattern allows an interface to be extended without breakingpre-existing clients.Over time, you will need to extend the interface to add new functionality. This pattern gives you more flexibility when you need to extendyour component because it removes restrictions that you would otherwise have felt. For instance, you are completely free to change thesize of the implementation class even if the interface has been derivedfrom.

Most changes to the implementation are hidden from clients.• This pattern reduces the maintenance costs for your component byallowing an implementation to be replaced or re-factored withoutimpacting clients of your interface.Over time, code becomes more difficult to maintain as new featuresare added. At some point it becomes more beneficial to completelyreplace, re-factor or redesign the existing code to allow it to performbetter or to allow for new functionality to be added.

Where this patternhas been used, this is significantly easier to do because the interface iswell encapsulated so that as long as the interface remains compatible,the underlying implementation can be completely re-factored orreplaced.• You have the freedom to choose a different implementation.Since this pattern hides so much of the implementation from clients ofyour interface you have more freedom to select the most appropriatebody for the circumstances. This can be done at compile time but alsoat run time for even more flexibility.

If you do need to dynamicallyload a body then you should use the Symbian OS ECom plug-inservice.34 Remember that, in either case, each of the different bodies34 See[Harrison and Shackman, 2007, Section 19.3] for details about ECom.HANDLE–BODY391needs to provide the same overall behavior as it’s no good if clientsstill compile but they then break at run time because your interfaceperforms in ways the client didn’t expect.• Your testing costs are reduced.Since the interface to your component is well encapsulated you willhave fewer side-effects to deal with during testing of the componentusing this pattern.

However, this pattern also makes it easier to createmock objects35 when testing other components by making it simpleto replace the real implementation with a test implementation.Negatives• Additional complexity can increase maintenance costs.If you hadn’t applied this pattern then you’d have one fewer class inyour design. Whilst this doesn’t sound like much, if you apply thispattern to a lot of interfaces then you can get into a situation whereclass hierarchies can be quite complicated.

This can make it harderto understand and debug your component as a result.• Additional overheads are caused by the extra indirection.By introducing an additional level of indirection this incurs smallexecution-time and code-size penalties for your component. Theextra function call used when calling the body class, and the extraobject allocation, leads to the loss of some CPU cycles whilst theextra class requires more code.Example ResolvedAs seen in the solution above this is a very simple pattern, but it is alwaysworth looking at how it has been used in a real example.As described above, Symbian OS provides an interface for clients touse HTTP functionality.

One of the interfaces exposed by this componentis the RHTTPSession class which represents a client’s connection witha remote entity and allows multiple transactions to take place usingthis connection. This class is the starting point for developers using theSymbian OS HTTP service.Since it was important to provide a stable interface to clients whilstnot restricting future growth, this pattern was used.HandleRHTTPSession is the handle as it provides the interface used by clients.In this case it is an R class to indicate that it provides access to aresource owned elsewhere, which in this case is in the HTTP protocolitself.35 en.wikipedia.org/wiki/Mock object .−392MAPPING WELL-KNOWN PATTERNS ONTO SYMBIAN OSThe following code shows the most important points of this classfrom the point of view of this pattern.

The full details can be found inepoc32\include\http\rhttpsession.h.class CHTTPSession; // Note the forward declare of the bodyclass RHTTPSession{public:IMPORT_C void OpenL();IMPORT_C RHTTPHeaders RequestSessionHeadersL();...private:friend class CHTTPSession;CHTTPSession* iImplementation; // Note the pointer to the body};The following is the simplest of several different options for beginningan HTTP session.

This method, OpenL(), acts as the factory constructionfunction for RHTTPSession and allows clients to create and initialize asession with the HTTP service.This function call constructs the body by simply calling its NewL().Slightly unusually, the handle function, OpenL(), has a different nameto this body function. This simply reflects the fact that the handle is anR class whilst the body is a C class which means developers wouldn’texpect to see a NewL() on RHTTPSession whilst they would onCHTTPSession. The functions also act very slightly differently in thatOpenL() is called on an existing object whilst NewL() is a static functionand doesn’t need to be called on an object.Finally, note the use of Fail Fast (see page 17) to catch clients who callthis function twice which would otherwise cause a memory leak.EXPORT_C void RHTTPSession::OpenL(){__ASSERT_DEBUG(iImplementation == 0,HTTPPanic::Panic(HTTPPanic::ESessionAlreadyOpen));iImplementation = CHTTPSession::NewL();}The following shows an example of one of the handle’s functions thatsimply forward the call on to the body to deal with.EXPORT_C RHTTPHeaders RHTTPSession::RequestSessionHeadersL(){return iImplementation->RequestSessionHeadersL();}HANDLE–BODY393BodyThe CHTTPSession class forms the body in this use of the pattern asfollows:class CHTTPSession : public CBase{public:static CHTTPSession* NewL();RHTTPHeaders RequestSessionHeadersL();inline RHTTPSession Handle();...private:CHeaderFieldPart* iConnectionInfo; // The proxy or connection detailsRArray<CTransaction*> iTransactions; // All the open transactionsRArray<THTTPFilterRegistration> iFilterQueue;...};The NewL() isn’t shown because it is implemented in the standardSymbian way as a two-phase constructor.

However, here is the implementation of CHTTPSession::RequestSessionHeadersL() whichprovides the functionality for RHTTPSession::RequestSessionHeadersL().Note the use of Lazy Allocation (see page 63) to create the requestheader collection class on demand. Apart from that and returningan object on the stack from the function, there is nothing unusualhere.RHTTPHeaders CHTTPSession::RequestSessionHeadersL(){// Create the session headers if necessaryif (iRequestSessionHeaders == NULL){iRequestSessionHeaders = CHeaders::NewL(*iProtocolHandler->Codec());}return iRequestSessionHeaders->Handle();}The one additional function we should discuss is the Handle() function provided by the body which returns an RHTTPSession instancewhich uses the current object as its body.

Providing a Handle() function on a body class may look slightly odd at first but points to aninteresting side-effect which the HTTP framework takes full advantage of.If you take a closer look at RequestSessionHeadersL(), youwill see that it returns an object by value rather than a reference orpointer to one. This is because RHTTPHeaders is also implementedusing this pattern and is a handle to a CHeaders object.

This means394MAPPING WELL-KNOWN PATTERNS ONTO SYMBIAN OSthat RHTTPHeaders is an object of size 4 bytes, because of its iBodypointer, which makes it efficient to pass by value on the stack.The CHTTPSession::Handle() method works in the same wayand creates a new handle to itself. The function can be inlined becauseit’s only ever used within your DLL and so there’s no danger of it leakingout into client DLLs and causing compatibility problems in the future. Ifyou were wondering why CHTTPSession was declared as a friend byRHTTPSession it’s so the following would be possible:inline RHTTPSession CHTTPSession::Handle(){RHTTPSession r;r.iImplementation = this;return r;}This isn’t an essential part of implementing this pattern but can beuseful in other implementations as you can use the handle class in asimilar way to the way you would treat a pointer to the body class butwith more protection.

Note that this all works because only shallowcopies of the handle class are made. Hence copying a handle couldmean that there are two handles pointing to the same body just as if you’dcopied a pointer. This means the ownership of the handle classes shouldbe treated carefully to avoid double deleting the body.Other Known Uses• Image ConversionThis component makes use of this pattern in both CImageDisplayand CImageTransform to provide these widely used classes withthe flexibility to be extended in future to allow different image formatsto be displayed and transformed through the same interface by simplychanging the underlying body providing the implementation of theinterface.• EComThe Symbian OS ECom plug-in service is based on this pattern asframeworks interact with plug-ins through a handle class.

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

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

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

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