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

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

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

This class is expected to beopen for the entire time that you wish to use the property and only closedwhen you have completely finished with the property.class RPropertyPublisher{public:void OpenL(TPropertyValue& aValue);void Close();void PublishL();private:RProperty iProperty;TPropertyValue& iValue;};Note that we have chosen to use Escalate Errors (see page 32) to handleany errors that occur but you are free to choose a different strategy.The following function has the responsibility of preparing to publishnew values of the property. The property is defined here so that theproperty only exists whilst this class is Open though for your specificimplementation you might find that some notional manager class is betterplaced to actually manage the lifetime of the property separately from thelifetime of this class.RPropertyPublisher::OpenL(TPropertyValue& aValue){iValue = aValue;// NB Define() is a static functionTInt result = RProperty.Define(KSharedPropertyCategory,23 Assuming that the TPropertyValue object being referenced has a longer lifetimethan RPropertyPublisher, of course.122EVENT-DRIVEN PROGRAMMINGESharedPropertyKey1,RProperty::EByteArray,KSharedPropertyReadPolicy,KSharedPropertyWritePolicy,sizeof(TPropertyValuePckg));// There’s no need to leave if it has already been definedif (result != KErrAlreadyExists && result != KErrNone){User::Leave(result);}// Whilst this is optional it does make subsequent publishing fasterUser::LeaveIfError(iProperty.Attach(KSharedPropertyCategory,ESharedPropertyKey1));}The following function has the responsibility of cleaning up the property.

In particular, it deletes the property so that we don’t unnecessarilywaste RAM for a property that isn’t required any more. The property isdeleted here so that we maintain the class invariant: the property is onlyvalid whilst the class is open.RPropertyPublisher::Close(){iProperty.Close();// NB Delete() is a static functionRProperty::Delete(KSharedPropertyCategory, ESharedPropertyKey1);}The following function simply has to package up a copy of the newvalue and publish it via its handle to the underlying property. The eventconsumer calls this function each time that it wishes to publish thevalue.void RPropertyPublisher::PublishL(){// Prepare packaged copy of the referenced valueTPropertyValuePckg valuePckg;valuePckg() = iValue;User::LeaveIfError(iProperty.Set(valuePckg));}Event ConsumerThe following class encapsulates the subscription to changes in theproperty.

This class derives from CActive so that the event consumerthread doesn’t have to stop executing whilst it is waiting for an eventsignal. For more details see Active Objects (page 133).PUBLISH AND SUBSCRIBE123This class is not responsible for handling the event signal; instead ituses Event Mixin (see page 93) to allow another class within the eventconsumer thread to take responsibility for this. Not only does this makethe implementation easier to understand here but it is an example of anevent-driven chain.class MEventMixin{public:void HandlePropertyChangeL(TPropertyValue aNewValue);};The following code is usually defined in a separate header file to theabove to allow the packaging also to be decoupled.class CPropertySubscriber : public CActive{public:static CPropertySubscriber* NewL(MEventMixin* aCallback);∼CPropertySubscriber();protected:void ConstructL();// From CActivevoid DoCancel();void RunL();private:CPropertySubscriber(MEventMixin* aCallback);private:RProperty iProperty;MEventMixin* iEventMixin;};For brevity, we’ve not shown the implementation of the constructorwhich simply stores the callback passed in as a parameter and sets up theactive object appropriately.

The NewL() is no different from a normaltwo-phase constructor implementation. However, the ConstructL() isresponsible for preparing its RProperty object for later use and startingthe calling Subscribe() for the first time via the RunL():void CPropertySubscriber::ConstructL(){// Note this is required for subscribers and is not optional, as it is// for publishersUser::LeaveIfError(iProperty.Attach(KSharedPropertyCategory,ESharedPropertyKey1));RunL();}124EVENT-DRIVEN PROGRAMMINGThe destructor is simply responsible for clearing up its resources:CPropertySubscriber::∼CPropertySubscriber(){Cancel();iProperty.Close();}The Cancel() above calls the following function if a Subscribe()call is outstanding:void CPropertySubscriber::DoCancel(){iProperty.Cancel();}Here is where the majority of the work is done, following the standardpublish and subscribe pattern of Subscribe() and Get() followed bythe handling of the event signal:void CPropertySubscriber::RunL(){User::LeaveIfError(iStatus);// Register for further event signals before handling the new valueiProperty.Subscribe(iStatus);SetActive();// Get the new valueTPropertyValuePckg valuePckg;User::LeaveIfError(iProperty.Get(valuePckg));// Send event signal on the event mixin to handle the valueiEventMixin->HandlePropertyChangeL(valuePckg());}ConsequencesPositives• This pattern reduces the power usage of your components.• The publish and subscribe service provided by the kernel is simple touse.• It offers a way to communicate values and event signals between eventgenerators and event consumers in different threads or processes.• Event generators and event consumers are very loosely coupled withfew static dependencies between them.

The only ones should becaptured in your sharedproperty.h header file.PUBLISH AND SUBSCRIBE125• It allows security checks to be performed separately on both eventconsumers and event generators.Negatives• It doesn’t support reliable event signals and hence can’t be usedin situations where an event consumer needs to be aware of everyintermediate property value.• It only supports warm event signals since the actual value of theproperty must be retrieved via RProperty::Get().• Event generators have no knowledge about whether there actually areany event consumers receiving the event signals.Example ResolvedTo resolve the mass storage example, the File Server, as the eventgenerator, takes the responsibility of defining a property through whichthe state of the mass storage drives are published to event consumerssuch as the MSA.

The MSA application simply subscribes to these eventsand updates its UI as appropriate.Shared DefinitionsThe following types are defined in usbmsshared.h: the shared categoryand four properties, including the one used by the MSA applicationto monitor the status of mass storage drives – EUsbMsDriveState_DriveStatus.// The publish and subscribe category for all USB Mass Storage events.const TUid KUsbMsDriveState_Category = { KFileServerUidValue };// The publish and subscribe event key enumerationenum TUsbMsDriveState_Subkey{EUsbMsDriveState_DriveStatus,EUsbMsDriveState_KBytesRead,EUsbMsDriveState_KBytesWritten,EUsbMsDriveState_MediaError};In addition, usbmsshared.h defines a data structure, TUsbMsDrivesStatus, that contains information on up to eight drives givingthe drive number and the state it is in:// Possible values for each of EUsbMsDriveState_DriveStatus status// codesenum EUsbMsDriveStates126EVENT-DRIVEN PROGRAMMING{/** File system not available for Mass Storage */EUsbMsDriveState_Disconnected=0x0,/** Host has required connection */EUsbMsDriveState_Connecting=0x1,/** File system available to Mass Storage */EUsbMsDriveState_Connected=0x2,/** Disconnecting from Mass Storage */EUsbMsDriveState_Disconnecting =0x3,/** Critical write - do not remove card */EUsbMsDriveState_Active=0x4,/** Connected, but locked with a password */EUsbMsDriveState_Locked=0x5,/** Connected, but card not present */EUsbMsDriveState_MediaNotPresent=0x6,/** Card removed while active */EUsbMsDriveState_Removed=0x7,/** General error */EUsbMsDriveState_Error=0x8};// The maximum number of removable drives supported by Mass Storageconst TUint KUsbMsMaxDrives = 8;// A buffer to receive the EUsbMsDriveState_DriveStatus property// For each drive there is a pair of bytes: the drive number// followed by the EUsbMsDriveStates status code.typedef TBuf8<2*KUsbMsMaxDrives> TUsbMsDrivesStatus;Event GeneratorThe File Server uses a class called RDriveStateChangedPublisherto publish the drive status information.

This is done in a very similar wayto the implementation given above, in that the class constructor takesreferences to the information to be published so that the user of the class,CDriveManager, simply has to ask it to publish the new value.One difference from the standard pattern implementation aboveis that the security policies to read and write the EUsbMsDriveState DriveStatus property are not defined in the shared classbecause it’s not strictly necessary.

Instead, they’re defined locally withinthe RDriveStateChangedPublisher implementation as:_LIT_SECURITY_POLICY_PASS(KMassStorageReadPolicy);_LIT_SECURITY_POLICY_S0(KMassStorageWritePolicy,KUsbMsDriveState_Category.iUid);This allows any event consumer to read the property but only the FileServer may publish the drive status information as required.Event ConsumerThe MSA application simply subscribes to the (KUsbMsDriveState Category, EUsbMsDriveState DriveStatus) propertyPUBLISH AND SUBSCRIBE127and passes each new value of the property on via the following eventmixin class:class MDriveWatch{public:virtual void DrivePropertyChange(TUsbMsDrivesStatus aDriveStates) = 0;};The MSA application contains a CMSManager class that derives fromMDriveWatch to handle the fact that the property has changed byunpacking aDriveStates and updating each drive icon in its UIappropriately.Other Known UsesThis pattern is used by many components throughout Symbian OS, forexample:• Time Zone ServerUses this pattern to provide notifications of changes to:• System-wide UTC offset changes, via the EUtcOffsetChangeNotification key• The current time zone, via the ECurrentTimeZoneId key• The home time zone, via the EHomeTimeZoneId key• The Next Daylight Saving Time Change, via the ENextDSTChangekey.See epoc32\include\tzupdate.h for more information on theshared types used.• Backup ServerUses this pattern to indicate whether a backup is in progress or notvia the (KUidBackupRestoreKey, KUidBackupRestoreKey)property.

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

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

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

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