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

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

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

The client, however,shouldn’t be troubled by the error.• Responses come from a remote device in response to a command thelocal device has sent and hence the client is expecting some kind ofresponse. In this protocol, the remote device thinks it’s done its job byresponding and we don’t automatically ask for a response to be sentagain. That’s left up to the client to decide.This behavior is implemented in the following function called by thestencil after any point that it finds an error with the received packet.

Notethat it calls some accessors on the stencil which, if the packet, is invalidcould cause problems. Hence you need to be very careful when doing328OPTIMIZING EXECUTION TIMEthis to ensure that the function can never fail. This usually means theaccessor has to return a value indicating that it couldn’t determine therequired information. For example, the PacketType() function returnsEInvalidPacketType if this value can’t be determined.void CSignallingChannel::InvalidPacket(CAvdtpInboundSignallingMessage& aMessage,TInt aError){switch(aPacket.PacketType()){case EDiscoverCommand:{// Send reject response to the remote device}case EDiscoverResponseAccept:{// Pass the error up to the client}...case EInvalidPacketType:{// Send the reject response to the remote device and// pass the error up to the client}}Other Known Uses• Symbian’s RfComm Protocol ImplementationThe pattern is used to process inbound messages for this Bluetoothserial port emulation protocol.• Symbian’s TCP/IP stackThe Data Press pattern is expressed as a template class that takesa variety of different stencils to process data for different protocols.This data press is not stored on the heap, but instead is created asneeded on the stack.

Since the data that is being processed is held ina separate heap that serves as a data bank, and is just referred to bya handle held by the template class (in a similar way to our exampleabove), this is a cheap and efficient way of managing the data to beparsed.Variants and Extensions• Long-Running ProcessingIn the pattern described above, the processing of the raw data happens synchronously during the NewData() event and may result inNewData() being called on the source. As middleware componentsDATA PRESS329are often stacked together, this could result in a long synchronous callfrom the bottom of the stack right up to the top.

This would makethe stack unresponsive to any new events during the processing of thepacket by the whole stack. This is because the processing is likely tobe running within the RunL() of a low-level active object and wouldhence be stalling the active scheduler. If this could be a problem thenit is advisable during the NewData() event to setup an asynchronouscallback to handle the actual processing of a packet, perhaps usingthe Symbian OS class CAsyncCallBack.• Field CachingThe implementation above shows the stencil header field accessorsinterpreting the raw data every time the function is called.

For fieldsthat are accessed frequently or are complex to parse, you mightimprove your execution time by caching their values as data membersin the stencil.• Multiple Stencil InstancesThere can be scenarios where you are able to process multiple packetssimultaneously.

This can be done by the data press pre-allocating morethan one instance of a stencil class. The main thing to remember whendoing this is that each stencil must operate on a different piece of rawdata.References• Immortal (see page 53) is used by the data press when pre-allocatinga stencil object.• Escalate Errors (see page 32) is used to simplify the error handlingwithin the stencil object by escalating all errors up to the data pressobject to handle.• Event Mixin (see page 93) is employed by the data process to providethe stencil with an interface through which it can pass the results ofits interpretation of each packet.• Flyweight [Gamma et al., 1994] is related to this pattern.

The ideaof a Flyweight is to use a low footprint class to represent a smalldata feature, say a letter in a word-processing program. A small setof Flyweight objects are created and held for frequent reuse withina wider program. The objective is to reduce allocation costs but theFlyweight class is really more of a passive data model than the datapress, which both models the data and modifies it.9Mapping Well-Known Patternsonto Symbian OSIn this chapter, we describe the following well-known design patternsand how they are applied and used on Symbian OS:• Model–View–Controller (see page 332) was first described in[Buschmann et al., 1996]. Symbian OS ensures every applicationuses this or a variant of this pattern so that they are easier to maintain,test and port between different mobile devices.• Singleton (see page 346) was first described in [Gamma et al., 1994].This popular and sometimes controversial pattern (used to ensurean object is unique) is included because the standard mechanism ofimplementing it using writable static data hasn’t always been availableto Symbian OS developers.

Whilst it is available in Symbian OS v9,alternative solutions are recommended for widely used DLLs due tothe large impact it can have on memory usage.• Adapter (see page 372) was first described in [Gamma et al., 1994]. Itis commonly used for at least the following three use cases: preservingcompatibility by enabling an interface to continue to be providedthat is re-implemented in terms of an upgraded interface; wrappingexisting components to allow them to be ported to Symbian OS; andsupporting a choice of components at run time by adapting them to aplug-in interface.• Handle–Body (see page 385) was perhaps first described in [Coplien,1991].

This pattern introduces an additional layer of abstractionbetween the client of an interface and its implementation. This isparticularly useful for developers using Symbian OS as it not onlyensures that your components are flexible enough to allow easyextension in future but also because it gives you more freedomto extend them in a compatible way without the clients of yourcomponent having to make any changes as a result.332MAPPING WELL-KNOWN PATTERNS ONTO SYMBIAN OSModel–View–ControllerIntentAllow an interactive application to be easily extended, ported and testedby dividing the responsibility for managing, displaying and manipulatingdata between three cooperating classes.AKAMVCProblemContextYou wish to create an interactive application with a flexible human–computer interface1 that targets as many Symbian OS devices as possibleacross more than one GUI variant.Summary• You wish to be able to easily port your application between thedifferent GUI variants based on Symbian OS.• You want to be able to easily maintain and extend your applicationover time.• You want to be able to test as much of your application as possibleindependently of the GUI variant to reduce your testing costs.DescriptionSymbian OS supports multiple GUI variants, which are supplied by UIvendors as a layer on top of Symbian OS.

By supporting multiple GUIvariants, Symbian OS enables device creators to differentiate productsbased on form factor, UI ‘look and feel’, and interaction style. Forapplication developers, the most important GUI variants are S60 andUIQ. The third GUI variant, MOAP, is widely used on Symbian OSphones in Japan, but is not open to native third-party applications so wedon’t focus on it in this pattern.Historically, S60 has been associated with classic smartphone designsbased on small but high-resolution displays and key-driven operation,while UIQ has emphasized larger displays with pen-driven operationand flippable orientation, evolving from its early support for tablet-styledevices to supporting the signature Sony Ericsson ’flip’ phones. More1 Derived from the intent of Model–View–Controller defined in [Buschmann et al.,1996].MODEL–VIEW–CONTROLLER333recently S60 and UIQ have shown signs of convergence, as UIQ3has introduced support for purely key-driven interaction and S60 hasindicated future intentions to support pen-based interaction styles.Their ‘look and feel’, however, remain distinctively different, and thereare significant differences in implementation detail.

Each defines its ownhierarchies of concrete controls (dialogs, windows, and so on), and whileboth share a task-based approach, there are subtle differences in theirimplementation of the task and application models.Although the different GUI variants all derive from common Symbian OS frameworks, they encapsulate different vendor choices andassumptions about device form factors and interaction styles. This leadsto non-trivial differences between the variants which means developershave to customize their applications for each GUI variant they wishto support. Any application that doesn’t control its UI dependencies ismore difficult to port between multiple, independently evolving targetGUIs so we need to avoid a monolithic approach to creating applications.On any operating system or platform, an interactive application withmore than a trivial implementation typically has the following responsibilities, regardless of how they are assigned within the design:• code that manages and manipulates the internal logical state of theapplication• code that displays a representation of the current application state• code that reacts to events from the end user to manipulate both of theabove.ExampleConsider a contacts application which at its simplest allows the enduser to store and later retrieve the contact details of the people thatthey know.

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

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

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

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