2. Author Biographies
M. ASHOK RAJA
Ashok Raja has 5+ years of experience in the IT industry. He has been associated with various domains including nuclear pow-
er, telecom, embedded system, and user personalized applications.
RISHI SHARMA
Rishi Sharma has 8+ years of experience in the IT industry. He has been associated with various domains like NMS, K–Java
embedded system, telecom, high availability, and user personalized applications.
3. GSG TECHNICAL JOURNAL
Motorola Internal Use Only
DESIGN PATTERNS FOR SMALL DEVICES
Rishi Sharma, Ashok Raja
Abstract: Design patterns are recurring solutions to
software design problems found repeatedly in real-world
software development. It may not always be possible to get
the design right the very first time. One of the major
advances in software development in the past decade has
been the acceptance of the notion that the process of
building a software system should be an evolutionary which
means learning from the past experience and feed backing
the learning to new software systems. Over the period of
time the knowledge of how to design generic, robust, and
scalable software architectures and design has matured.
These reusable solutions to problems have resulted in
considerable savings in terms of costs and time. The
objective of this paper is to imply same theory to embedded
system and suggest three design patterns that help
development and test teams with shorter development and
test cycles.
Index Terms: Design Pattern, small devices, Virtual
Component, Hierarchical State, LED [Light Emitting Diode]
Error and embedded applications.
INTRODUCTION
Working in an embedded environment has its own
challenges. This paper tries to address few of the
following design concerns.
• Memory is precious: Desktop computing has
higher memory capacity (in order of gigabytes).
Getting desktop applications running in
embedded environment where memory is limited
poses challenges to designers as the memory is
limited (in order of megabytes). One example is
trying to synchronize an Outlook address book
with mobile’s contact data.
• Processing speed is limited: Each machine cycle
counts. Use of the composite pattern as a
structural pattern to have a multi level object
hierarchy may add to the processor overhead
preventing the actual code segment to slow.
This impacts the ergonomics of a mobile system.
• Flash/Disk space is a constraint: On a mobile
device the storage is divided between application
space and user space. The physical size of the
date book application on the disk is an example
of application space where as how many meeting
notices a user can store is an example of user
space. Storage needs to be considered part of the
design and new patterns like compression
patterns need to evolve to address such needs.
• Remote Testing of embedded systems: Test
design patterns are to testing what software
design patterns are to programming. There is a
limited support to debug and test in an embedded
environment. Test designs patterns needs to
evolve to support testing of embedded
systems.
Objective:
From our working experience in embedded domain
we have often seen a system divided into small
modules and each module being modeled in form of
state machines. Our analysis shows that in doing so,
one may miss out to pull the commonality of each
module and come up with a generic solution which is
common to each module. This will result in
decreasing the size of a software system and reduced
memory footprint. The objective of this paper is to
highlight the importance of design patterns for small
devices so as to make identification of an appropriate
design pattern as a mandatory activity during the
design phase for embedded systems within Motorola.
We focus on three less common design patterns
which we believe should become part of Motorola’s
design checklist for embedded system architecture
and design. Following three design patterns are
explained with their applicability in the embedded
domain.
1) Hierarchical State Design Pattern
2) Virtual Component Design pattern
3) LED Error Design pattern
I. HIERARCHICAL STATE DESIGN PATTERN
Pattern Name:
Hierarchical State Design Pattern
Problem description:
A conventional finite state machine is designed as a
two dimensional array with one dimension as the
state and the other dimension specifying the input
signal to be handled. The state machine determines a
message handler to be called by maintaining the
current state and the received input signal. In a real
life scenario, a task usually has a number of states
along with many different types of input signals. This
leads to complexity in the message handler code as
the number of states increases in the system and the
size of code becomes larger and unmanageable.
Motivation:
The hierarchical state machine design pattern avoids
this problem by recognizing that most states differ in
the handling of only a few messages. When a new
4. GSG TECHNICAL JOURNAL
Motorola Internal Use Only
hierarchical state is defined, only the state specific
handlers need to be specified.
Pattern overview:
In a conventional state machine design, all states are
considered at the same level. The design does not capture
the commonality that exists among states. In real life,
many states handle most messages in a similar fashion
and differ only in handling of few state specific messages.
Even when the actual handlings differ, there is still some
commonality. The hierarchical state design pattern
captures the commonality by organizing the states as a
hierarchy. The states at the higher level in the hierarchy
perform the common message handling, while the lower
level states inherit the commonality from higher level
ones and perform the state specific functions.
Structure:
To understand the pattern lets look at an example of a
conventional way of designing state machines. Error!
Reference source not found. below describes the state
transition diagram for an active standby pair. The design
here assumes that the active and standby states are being
managed by an external entity.
The different states for the state machine are Active,
Standby, Suspect and Failed. The input signals to be
handled are Switchover, ‘Fault Trigger’, ‘Diagnostics
Passed’, ‘Diagnostics Failed’ and ‘Operator Inservice’.
This means there are 4 states and 5 handlers. During
design the designer needs to consider that the system can
be in any of these 4 states while any of those 5 input
signals arrive. Hence the code will have a two
dimensional array of 4 x 5 i.e. 20 different combinations.
Five handlers for each state need to be managed assuming
all the states are at same level increasing the array size to
20.
Now let’s try to apply the Hierarchical State Design
Pattern to this example. The following state transition
diagram in Fig.2 recasts the state machine by
introducing two levels in the hierarchy. Inservice and
OutOfService are the two high level states that
capture the common message handling. The Active
and the Standby states are low level states inheriting
from the Inservice state. Suspect and Failed are low
level states inheriting from the OutOfService state.
It is recommended to define a base state and then
derive child states from the base state. Fig.3 clearly
illustrates the state hierarchy. A base UnitState is
defined and the Inservice and the OutOfService, high
level states inherit from the UnitState which is at the
highest level.
As one can see with 2 states and 3 messages the first
level two dimensional array is reduced to 2 x 3 i.e. 6
handlers.
Implementation:
This section describes activities associated with
implementing the pattern.
1) Define the base class e.g. Unitstate that provides
a "do nothing" implementation for all handlers.
Fig. 1 – Conventional state machine
Inservice.Active
Inservice.Standby Outofservice.Suspect
Outofservice.Failed
Switchover Switchover
Fault Trigger
Fault Trigger
Diagnostics
Passed
Operator
Inservice
Diagnostics
Failed
Inservice
OutOfService
Fig. 2 – Hierarchal state machine
Fig.3 – State hierarchy
5. GSG TECHNICAL JOURNAL
Motorola Internal Use Only
Thus an inheriting state has to provide an
implementation only for the methods it supports.
2) Define derived classes e.g. Inservice,
Out_Of_Service from the base class and define the
common implementation here.
3) Continue to define nested derived states e.g. Active,
Standby from the Inservice class and suspect, failed
from the OutOfService class and implement a state
specific functions.
4) Define appropriate handlers methods for each of the
above states.
5) Provide a main message handler for invoking the
appropriate handler based on the type of the input
signal.
Base states handle most of the message processing. In
some cases, the inheriting states perform some additional
action and call the handler for the base state for the
common part of the handling.
Applicability:
This pattern reduces code repetition between handlers
and minimizes maintenance overhead for state machine
designers. The design pattern is applicable for state driven
message based software systems.We see it’s applicability
in P2K (Platform 2000) and upcoming Linux-Java
platform for mobile devices as following:
As of now different applications like PIM (Personal
Information Manager) and SDL (Shortcuts Date book &
Local features) interact with Mobile Application
Framework separately. Each of the applications in the
above features calls same method to post a message to the
Mobile Application Framework. Using the Hierarchical
State Design Pattern such common states can be pulled
out of the scope of the applications and defined as
common states for all applications thus reducing the total
number of states in the system and their handlers.
Known uses:
The pattern is used in maintaining synchronization in
digital communication systems, e.g. digital trunk
synchronization procedures. This design pattern provides
a broad framework for implementing such synchronous
systems. The pattern can also be applied in more general
scenarios where periodic message communication is
involved between entities to exchange state information.
A good example would be routing protocols where
periodic routing updates are used to keep different routers
in synchronization with each other.
II. VIRTUAL COMPONENT DESIGN PATTERN
Pattern Name:
Virtual Component Design Pattern
Problem Description:
Memory-constrained applications can not afford to
waste storage on unused or rarely used functionality.
Motivation:
Identify the components whose interfaces represent
the building blocks of the application being
developed and implement using on demand concrete
components.
Pattern Overview:
The Virtual Component Design Pattern provides an
application-transparent way of loading and unloading
components that implement middleware software
functionality. Memory constrained applications might
have been developed manually and hard-coded to use
low-level languages and software tools, which is
tedious and error-prone. The growing use of
middleware provides a more powerful distributed
computing model that enables clients to invoke
operations on reusable components without hard-
coding dependencies on their location, programming
language, operating system platform, and
communication protocols.
Providing all the features in one implementation
increases the footprint, which makes it unsuitable for
use in memory-constrained applications. Two types
of footprint are important to memory-constrained
applications.
• Static footprint: holds the image of an
application. This storage can reside in the
ROM where the program is stored. This is
time-invariant since it does not change as the
application runs.
• Dynamic footprint: represents the memory
used by a running instance of the
application. This is a sum of the code, the
heap, and stack size.
Structure:
The Virtual Component Design pattern includes the
following:
• Component: Defines the interface to the
capabilities provided by acomponent in
Fig.4 and represents the contract between
the component and its clients.
• Concrete component: Provides the actual
implementation of acomponent. The Virtual
Component Design Pattern avoids loading
and/or deploying concrete components into
applications that do not require their
capabilities.
• Component factory: Defines an interface and
a factory method that creates components.
6. GSG TECHNICAL JOURNAL
Motorola Internal Use Only
• Concrete component factory: Defines a concrete
implementation of the component factory that
produces concrete components.
• Loading strategy: Defines how and when a
concrete component is loaded and instantiated.
• Unloading strategy: Defines how and when a
concrete component and its associated resources
are unloaded.
To illustrate the collaborations performed by participants
in the Virtual Component Design Pattern, following three
different loading scenarios exists:
Scenario 1:
Fig.4 shows an eager static loading strategy, where the
application loads the entire concrete component during
program startup.
• At the application startup time, all needed
components are loaded and initialized.
• The application code creates a concrete
component via a component factory, which can
either provide a pre-initialized component or
create a new one. No subsequent dynamic
loading is necessary in this case.
• The application code then uses the component.
• In this scenario the unloading policy does
nothing, i.e., it is a no-op. Unloading a
component that is not used at a particular time or
during a particular path through a program
defeats the purpose of eager static loading since
additional latency will be required to reload the
component if it is needed later. The main goal of
eager static loading is to ensure that whatever is
used by the system will already be in place when
needed. This property is desirable for
applications that cannot tolerate jitter introduced
by lazy loading and instantiation.
Scenario 2:
Fig.5 shows an eager dynamic loading strategy. In this
strategy, a concrete component factory loads the entire
concrete component when the application resolves a
reference to the component at the run-time, rather
than loading it eagerly during program startup.
• The application code creates a concrete
component via a component factory.
• The eager dynamic loading strategy
associated with the concrete component
factory loads the concrete component.
Depending on how the middleware was
configured, the factory can create different
types of concrete components.
• The application code then uses the
component.
• Component use is reference counted, and
when a component reference count drops to
zero the unloading strategy associated with
the component is invoked.
Scenario 3:
Fig.6 shows a lazy dynamic loading strategy. This
strategy defers loading the concrete component until
it is actually accessed by a client, rather than loading
it when it is requested by the application.
• The application code creates a concrete
component via a component factory.
• The concrete component factory creates and
returns a reference to a proxy for the
concrete component. This proxy knows how
to load the component’s functionality and
data when it is accessed.
• The application code then uses the
component via its proxy, which triggers the
proxy to load the component’s functionality
and data. Depending on how the middleware
was configured, the proxy can load different
types of concrete components.
• Component use is reference counted, and
when a component reference count drops to
zero the unloading strategy associated with
the component is invoked.
Fig.4 – Eager Static loading strategy
Fig.5 – Eager dynamic loading strategy
7. GSG TECHNICAL JOURNAL
Motorola Internal Use Only
Implementation:
This section describes the activities associated with
implementing the Virtual Component Design Pattern.
1) Partitioning the middleware into a set of decoupled
components with well-defined interfaces: Required
components are those required by any application
that might use the middleware since they are
fundamental to its internal operational behaviour. In
contrast, optional components are those that may be
used by specific applications. Identify the optional
components in the middleware and make them into
virtual components. Each virtual component will be
represented by a common abstract interface, a
concrete implementation, and a loading strategy.
2) Define implementation strategies for concrete
components: Some components identified in step 1
may have more than one implementation alternative.
Where alternative implementations exist for a
component, or where a set of different
subcomponents work together to implement a
component, apply the Component Loading Strategy
to define each concrete component implementation
for the virtual component interface.
3) Define the component loading strategy: Define a
mean to configure which loading strategy should be
used for each concrete component in the middleware.
4) Define the concrete component unloading strategy:
Depending on application characteristics, different
unloading strategies can be used. At one end of the
spectrum, we could have an unloading strategy that
does nothing, i.e., it could be a Null Object.
Conversely, we could have an unloading strategy that
unloads all the resources associated with the
component, including the associated library.
Applicability:
• In present P2K (Platform 2000) architecture,
phonebook can be configured to make use of
Virtual Component Design Pattern so as to load
the contacts based upon the user selection.
• The static and dynamic footprint of the
middleware can be adapted to suit the needs of
the application. For example, any particular
component that is known to be unused can
be eliminated from the static footprint. In
addition, only components in active use are
included in the dynamic footprint.
• It allows middleware developers to offer
alternative implementations for components
of their system, which improves middleware
flexibility by supporting different
application requirements.
Known uses:
Product demos are an example of the Virtual
Component Design Pattern. To reduce theft, many
stores have resorted to displaying either non-
functional products, such as electronic devices, or
only boxes that contain no products, such as software.
The actual products reside somewhere back in the
warehouse. From the outside, the box appears like it
has a real product inside, but it is just a virtual
product. When a customer wants to purchase such a
product, they place the box in their cart and carry it to
the checkout. This “product fault” results in a
checkout clerk fetching the real product to place it
into the box. This entire process happens (almost)
transparently to the customer. When the customers
get home, they have their real product in hand.
III. ERROR LED DESIGN PATTERN
Pattern Name:
Error LED (Light Emitting Diode) Design
Pattern
Problem description:
While a test is in progress it is difficult to find the
status of the embedded device which does not have a
display associated with it. Debugging links (e.g. a
JTAG link), or a serial link (based on RS-232) take
time and including suitable ports on production
system may not be practical or cost effective
Motivation:
This Design pattern is intended to support
development and testing of reliable embedded
systems using low-cost embedded hardware with
severe memory constraints. Typical implementations
will employ embedded microcontrollers with a few
kilobytes of available RAM.
Pattern overview:
Many embedded systems have little or no user
interface. There is not generally a screen on which
you can display error messages or warnings to the
user.
Fig.6 – Lazy dynamic loading strategy
8. GSG TECHNICAL JOURNAL
Motorola Internal Use Only
While working on a system prototype, or performing
maintenance in the field, it is difficult to tell that the
system is “alive” - that it has power or the scheduler is
running. Error LED Design Pattern addresses this issue.
Structure:
Every time we implement an embedded system, the first
task we include is one that flashes a “heartbeat” LED.
Wherever possible, this LED stays with the system, right
into production.
This simple technique provides the following key
benefits:
• The development team, the maintenance team,
and, where appropriate, the users, can tell at a
glance that the system has power, and that the
scheduler is operating normally.
• After a little practice, the developer can tell
“intuitively” - by watching the LED – whether
the scheduler is running at the correct rate: if it is
not, it may be that the timers have not been
initialized correctly, or that an incorrect crystal
frequency has been assumed.
• By adding the “Heartbeat” task to the scheduler
array after all other tasks have been included, the
developer can tell immediately if the task array
is large enough to match the needs of the
application.
Implementation:
To implement ERROR LED, a single LED is used to
report error codes to the developer or tester. In most
cases, we like to base the Error LED on a Heartbeat LED
so that, if there are no errors, we see the usual 0.5 Hz
signal. If there is a problem, the display changes, and - by
observing different pulse rates - we can often identify the
cause. Following are the steps for implementation.
Use an error variable, and maintain a list of error codes.
In the event of an error, adjust the output of the ERROR
LED accordingly.
• Initialize the ERROR LED by setting the
appropriate pin to General Purpose Input Output
Register.
• If Error has occurred, change the state from OFF
to ON indicating that an error has occurred.
• LED can be flashed depending upon the
frequency set.
Applicability:
Use of this technique may help to improve system
reliability since it provides the developers of the system
with an indication of its health throughout the
development lifecycle. This provides a low-cost, non-
invasive means of error reporting.
Known uses:
Typical application areas for this type of software
range from passenger cars and aircraft to common
domestic equipment, such as washing machines and
microwave ovens.
CONCLUSIONS:
The Virtual Component Design Pattern allows
developers of standards-based middleware to offer a
large set of functionality to the users while keeping
the static and dynamic memory footprints
proportional to the features actually used.
The Hierarchal State Design Pattern allows for
organizations of states in order to remove duplication
of code and preserving the memory footprint of the
software system.
The LED Error Design Pattern provides a convenient
and economical way to identify major faults in an
embedded system
In future publications, we intent to cover the Wizard
Dialog Design Pattern, the Cascading Menu Design
Pattern, and the Slide Show Design Pattern which
address some of the challenges of the user interface
for small devices.
REFERENCES:
[1] Design Patterns Element of reusable object oriented
software - Eric Richard Ralph John, section 1.3
[2] Code Complete- Steve McConnell, part-1 key
construction decisions, p. 61
[3] EJB Design Patterns - Floyd Marinescu , chapter 9, p.
199
[4] Applied java patterns - Stephen A. Stelting, Olav
Maassen, chapter 3, p.157
[5] Doing Hard Time: Developing Real-Time Systems
with UML, Objects, Frameworks and Patterns-Bruce
Powel Douglass, chapter 7 p.328
ABOUT THE AUTHORS
Rishi Sharma has 8+ years of
experience in the IT industry. He has
been associated with various domains
like NMS, K–Java embedded system,
telecom, high availability, and user
personalized applications.
Ashok Raja has 4+ years of experience
in the IT industry. He has been
associated with various domains
including nuclear power, telecom,
embedded system, and user personalized
applications.