Главная » Просмотр файлов » Programming Java 2 Micro Edition for Symbian OS 2004

Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 58

Файл №779882 Programming Java 2 Micro Edition for Symbian OS 2004 (Symbian Books) 58 страницаProgramming Java 2 Micro Edition for Symbian OS 2004 (779882) страница 582018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

It allows the presentation ofthe data (the views) to be decoupled from the engine and its data (themodel). It also allows for multiple (and simultaneous) views of the samemodel (for instance, the same data might be presented as both a table anda pie chart). In practice, implementations of the MVC pattern are morecomplicated than the simplistic example shown in Figure 6.1, involvingmultiple concrete View classes (all deriving from an abstract View class),possibly each with an associated concrete Controller (deriving froman abstract Controller).Viewnotify user inputControllernotifyUserInput()notifyDataChanged()repaint()notify datachangedset data stateModelgetState()setState()Figure 6.1A simple example of the MVC pattern.322MAKING JAVA CODE PORTABLEview : Viewcontroller : ControllernotifyUserInput()model : ModelprocessinputsetState()processdatanotifyDataChanged()getState()repaint()Figure 6.2The interaction of objects in the MVC pattern.6.2.2 Model–View Design PatternThe Model–View design pattern (MV) is a simplified version of the MVCpattern.

The MV pattern is a specific variant of the Observer pattern (alsoknown as the Publisher–Subscriber). In the MV pattern, the View classcombines the functionality of the View and Controller classes in theMVC pattern. The View class in the MV paradigm will be familiar todesktop Java GUI programmers (even if they don’t realize it), as typicalapplication UIs make use of it. For example, the UI class shown below isessentially a View class in the MV pattern:public class MyCanvas implements MouseListener, KeyListener {public MyCanvas() {...addMouseListener(this);addKeyListener(this);}...}DESIGN PATTERNS323Under the MV pattern, application classes may be classified into oneof the two component groups:• the ModelThe model manages the application’s data. It responds to queries fromthe views regarding its state and updates its state when requested todo so by the views.

It notifies the views when the state of the datahas changed.• the View.The view presents a view of the model data. It responds to user input,instructing the model to update its data accordingly. On notificationof changes to the model data, it retrieves the new model state andrenders a view of the latest state of the data.This simpler pattern is perhaps more appropriate to simpler MIDlet applications.

It does not overcomplicate the class structure, and the applicationsoftware (and, indeed, the developers working on the application) maybe organized into two distinct groups, one responsible for the UI andthe other for the core application logic. It also means that porting theapplication between different MIDP devices that may utilize completelydifferent UI paradigms (for example, from a touch screen-based SonyEricsson P900 to a keypad-driven Nokia 6600) can be achieved withouthaving to touch the Model classes.A UML class diagram for part of a hypothetical MV-based applicationsupporting a pointer-based view and a keypad-based view is shown inFigure 6.3.6.2.3 Practical Application of Design PatternsThe reality is that these design techniques should be applied cautiouslyto wireless Java development.

Limitations such as the overall applicationsize may restrict the purest implementation. Even the smallest class cancreate an overhead of around 200 bytes and this will ultimately lead to alarger JAR file; class abstraction may need to be reduced to keep JAR filesizes realistic.

However, the theories and approaches are definitely validand will become more so as devices become less resource-constrained.A cursory look at Symbian OS devices based on MIDP 2.0 revealstwo user interface types. Phones such as the Series 60 Nokia 6600 offera keypad interface, whereas the UIQ-based Sony Ericsson P900 offers astylus-driven UI. In addition, the two phones also have different screensizes: 176 × 208 pixels for the Series 60 phone and 208 × 253 for theUIQ phone.

So porting an application from one device to the other mayinvolve changing the application code. By making use of the high-levelAPI, developers may be able to let the MIDP implementation itself take324MAKING JAVA CODE PORTABLE<<Interface>>ModelObserverModeldata state changegetState()setState()addObserver()removeObserver()notifyStateChanged()javax.microedition.lcdui.CanvasViewOnepaint()keyPressed()keyReleased()ViewTwopaint()pointerPressed()pointerReleased()get state, set stateget state, set stateFigure 6.3Multiple views supported by the Model–View design pattern.care of the UI for some applications. Once the developer ventures intothe realm of action games, however, it is a different matter altogether.Gaming applications generally require the use of low-level APIs, asthey give pixel-level control to the developer.

Objects such as sprites andlayers give the developer the ability to create animations that represent thevirtual world to the user. However, the underlying image files need to beoptimized for screen size and resolution. Other changes may be necessaryas well. For example, a level-based game ported to a device with a smallerscreen may need to have smaller levels and less complexity.Another issue with games is the capture of user input. Touch screendevices, such as the UIQ-based P900, handle this differently fromthose with a keypad.

As well as being captured by different methods(for example, in the Canvas class, by pointerPressed rather thankeyPressed), user input may need to be processed differently to ensurethe game still works correctly. In terms of design patterns this may requirean abstraction layer, such as the Controller in the MVC pattern, actingas an intermediary between the UI (the View) and the application gamelogic (the Model), ensuring that user input is processed appropriatelyregardless of the UI type.

Whatever design approach is adopted, it isimportant that the user interface is separated from the core logic of theapplication, allowing the game logic to remain the same across differentplatforms and UIs.DESIGN PATTERNS325<<Interface>>AbstractController<<Interface>>AbstractViewnotifyStateChanged()addController()removeController()paint()notify user inputnotifyUserInput()ConcreteViewOneConcreteControllerOnepaint()processInputOne()ConcreteViewTwoConcreteControllerTwopaint()processInputTwo()Modelget stategetState()setState()addView()removeView()set statenotify data state changedFigure 6.4 Separating the UI from the engine using abstraction.This yields a model where the development team in charge of creatingthe user interface can concentrate on recreating the UI for a new devicewithout having to understand the underlying game logic. They canrepurpose sprite graphics and make changes to user interaction classeswhile leaving the core game classes untouched.

Separating the UI canbe more easily approached with an abstraction of certain core classes(for instance an abstract View and an abstract Controller in the MVCdesign pattern). This provides a standard set of interfaces for the otherclasses within the application model to use. Extended classes then providethe implementation; for example, concrete View classes, possibly eachwith a dedicated concrete Controller (see Figure 6.4).This approach creates a set of reusable components that can beimplemented across a range of devices without having to rewrite theapplication on a grand scale.6.2.4 SummaryIn this section, we have seen how applications may be designed usingarchitectures derived from established design patterns. These patterns arelargely used for server and desktop applications; however, the principlesstill apply in the wireless world, although some of the roles may becompressed to suit the constrained nature of the environment.

While wewant to make sure we are not overcrowding the JAR file with unusedclass abstractions, we need to make our MIDlets as portable as possible.326MAKING JAVA CODE PORTABLE6.3 Portability IssuesThis section looks at a number of specific portability issues associatedwith the UI (both low-level graphics and higher-level UI components),optional and proprietary APIs, and download size limitations.To create a MIDlet that will run on a wide range of devices withdifferent form factors and functionality, it can be useful to identify thedevice’s characteristics either when the MIDlet is run, so that it can adaptits behavior dynamically, or when the MIDlet is provisioned, so that theserver can deliver an appropriately tailored JAR file.Runtime support for device identification is fairly limited: we can useSystem.getProperty() to identify the JTWI or MIDP version, andwe can identify the display characteristics using Canvas.getHeight(),Canvas.getWidth(), Canvas.isDoubleBuffered, Display.isColor() and Display.numColors().Currently, when downloading an application, it is generally left to theuser to click on the link appropriate to their phone (e.g.

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

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

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

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