BFH/HTA Biel/DUE/Course 355/ Software Engineering 2. Suppose you ll write an application that displays a large number of icons:

Similar documents
Flyweight Pattern. Flyweight: Intent. Use sharing to support large numbers of fine-grained objects efficiently. CSIE Department, NTUT Chien-Hung Liu

Tecniche di Progettazione: Design Patterns

Tecniche di Progettazione: Design Patterns

Flyweight Chain of Responsibility

Today. Last update: 5 June Structural Adapter Bridge Composite Decorator Façade Flyweight Proxy APPLICATION_1 APPLICATION_2. class APPLICATION_1

Unchained Malady A Tangle of Times

Assignment A7 BREAKOUT CS1110 Fall 2011 Due Sat 3 December 1

C o d i n g f o r i n t e r a C t i v e d i g i t a l M e d i a

Playing with Agent_SimpleSoccer. 1. Start the server 2. Start the agent(s) in NetBeans 3. Start the game: press k and b in the monitor window

Graphical User Interface in Java Using JavaFX

Assignment #3 Breakout! Due: 12pm on Wednesday, February 6th This assignment should be done individually (not in pairs)

CT PET-2018 Part - B Phd COMPUTER APPLICATION Sample Question Paper

Shooting Target Game. The user will be able to input a player s name and destroy a predefined number of dartboards before the game ends.

Assignment #3 Breakout!

Using MATLAB with CANoe

Praktikum Entwicklung von Mediensystemen Mobile Dienste für Studenten

An Architectural Approach for Improving Availability in Web Services

Based on a handout by Eric Roberts

F u n d a m e n t a l s o f G r a p h i c D e s i g n

Chapter 4 TOOLBOX AND SAMPLE BIKE BOULEVARD LAYOUT

EXAMINATIONS 2011 MID-YEAR COMP 102 INTRODUCTION TO COMPUTER PROGRAM DESIGN

Assignment 3: Breakout!

Williams, Justin à Player name (last name, first name) CAR

- 2 - Companion Web Site. Back Cover. Synopsis

On street parking manoeuvres and their effects on design

Triad Trickery: Playing with Sport and Games. Strategy

Beating Heart Simulator: Oral Report 2. Ashley Whiteside Nicole Rice Jacob Bauer

ISSUE #1 / SUMMER 2016

For IEC use only. Technical Committee TC3: Information structures, documentation and graphical symbols

Tech Suit Survey (Virginia LMSC)

PROJECTS STREETS

2017 IIHF BID REGULATIONS

EVT * -Pro Electronic Valve Tester

Working with Object- Orientation

Collision Avoidance System using Common Maritime Information Environment.

The importance of brand identity. Chapter one No escape! 2

Praktikum Entwicklung von Mediensystemen Simple and Secure Mobile Applications

Modeling Planned and Unplanned Store Stops for the Scenario Based Simulation of Pedestrian Activity in City Centers

Generating None-Plans in Order to Find Plans 1

Pedestrian Dynamics: Models of Pedestrian Behaviour

IBM Security IOC Manager 1.0.0

Iteration: while, for, do while, Reading Input with Sentinels and User-defined Functions

S.M.A.R.T.S. Stimulation Monitoring and Reservoir Testing Software tm

The MQ Console and REST API

Application of Bayesian Networks to Shopping Assistance

UNIVERSITY OF WATERLOO

Multivariable Predictive Control and its Application on the Solvent Dehydration Tower

IST-203 Online DCS Migration Tool. Product presentation

5.1 Introduction. Learning Objectives

Call to creators from the Downtown Winnipeg BIZ CHINATOWN BANNER COMPETITION 2016 YEAR OF THE MONKEY DEADLINE: JANUARY 26, 2016 CHINESE CENTRE

Real-Time Models for Real-Time Analysis. Motivation

Transposition Table, History Heuristic, and other Search Enhancements

Using what we have. Sherman Eagles SoftwareCPR.

Opleiding Informatica

IDENTITY GUIDE Elizabethtown College. All rights reserved.

STANDARDIZED CATCH RATES OF BLUEFIN TUNA, THUNNUS THYNNUS, FROM THE ROD AND REEL/HANDLINE FISHERY OFF THE NORTHEAST UNITED STATES DURING

OLYMPIC SPORT & ART CONTEST 2012

RIGHT TURNS AT INTERSECTIONS: ARE THERE ALTERNATIVES?

2600T Series Pressure Transmitters Plugged Impulse Line Detection Diagnostic. Pressure Measurement Engineered solutions for all applications

TORONTO VISION ZERO Improving Safety for Pedestrians and Cyclists Roger Browne, Manager Traffic Safety Unit October 11, 2018

Lab 1: Pressure and surface tension. Bubblers, gravity and the mighty paper clip.

#19 MONITORING AND PREDICTING PEDESTRIAN BEHAVIOR USING TRAFFIC CAMERAS

AC : MEASUREMENT OF HYDROGEN IN HELIUM FLOW

Hardware. Agile is all about innovation!

Effect of noise in the performance of the transducers in an ultrasonic flow meter of natural gas

RIBTS Scores * Program. Program RIBTS1 RIBTS2 RIBTS3 RIBTS4 RIBTS5 RIBTS6 RIBTS7 RIBTS8 RIBTS9 RIBTS10 RIBTS11

Training Throwers. UW-L Shot Putters UW-L Discus Throwers /3/2010. An Integrated Approach

Transform Your Classroom and Construct Learning with Geometry Golf

uemis CONNECT: Synchronisation of the SDA with myuemis

What s the difference?

Road design and Safety philosophy, 1 st Draft

2015 National Air Rifle League Program

THE WILDLIFE CONSERVATION AND MANAGEMENT ACT. (No. 47 of 2013)

h01: Perkovic Ch1 (Introduction to CS), 2.1, 2.2 (Expr, Vars, Assignment, Strings), 2.3 (Lists, Tuples)

ID: Cookbook: browseurl.jbs Time: 10:30:00 Date: 09/01/2018 Version:

Orion National Air Pistol League 2018 League Program

Wade Reynolds 1 Frank Young 1,2 Peter Gibbings 1,2. University of Southern Queensland Toowoomba 4350 AUSTRALIA

Mechanical Design Patterns

Digi Connect ME 9210 Linux: serial port 2 for JTAG modules

BPMN - IV. Rushikesh K Joshi IIT Bombay

Activity 5.1B Dragster Assembly Drawing

Planning and Design of Proposed ByPass Road connecting Kalawad Road to Gondal Road, Rajkot - Using Autodesk Civil 3D Software.

Diver Training Options

Critical Systems Validation

UNIT V 1. What are the traffic management measures? [N/D-13] 2. What is Transportation System Management (TSM)? [N/D-14]

Major League Baseball Offensive Production in the Designated Hitter Era (1973 Present)

SCORING FORMATIONS. Formation Junior and Main Duration of dancing and. Duration of dancing and music in finals of Girl. music in all other rounds

The Safety Case. Structure of Safety Cases Safety Argument Notation

Q2: Which instruments are necessary for monitoring the groundwater level?

PROCESS MONITORING AND CONTROL

Online League Management lta.tournamentsoftware.com. User Manual. Further support is available online at

The Safety Case. The safety case

Programming a recess with interrupted cut

EUROPEAN PARLIAMENT HEARING ON DOPING 29/11/2004. The Role of WADA in the fight against doping, Tom Dielen, Director European Regional Office WADA

Maximum Registration Numbers Overview

Application for diminishing or avoiding the unwanted. effects of traffic congestion

Walking for Health: Scheme page guide Contents

Creating a Walking Skeleton

INTRODUCTION AND METHODS OF CMAP SOFTWARE BY IPC-ENG

Cuisenaire Rods. A Guide to Teaching Strategies, Activities, and Ideas

Transcription:

Flyweight [GoF] Intent Object sharing to support large set of objects. Motivation Suppose you ll write an application that displays a large number of icons: Design Patterns Flyweight [GoF] 1

To manipulation the icons in the displayed pane, you want them to be ordinary objects. A naive implementation, however, would be prohibitively expensive. A flyweight is a shared object that can be used in multiple contexts simultaneously. In the example application given above, the icon pane (the view) conceptually contains many folder, Java source file, and other icon objects. However, there is only one real object instance for each icon type: iconpane foldericon foldericon foldericon javaicon javaicon flyweight pool The key concept is the distinction between intrinsic and extrinsic state: Intrinsic state: Stored in the flyweight, independent of the flyweight s context. Extrinsic state: State that depends on an varies with the flyweight s context. Design Patterns Flyweight [GoF] 2

Pane IconFactory * <<use>> AbstractIcon draw(pos, name) <<create>> FolderIcon JavatIcon PdfIcon byte[] icondata byte[] icondata byte[] icondata draw(pos, name) draw(pos, name) draw(pos, name) Applicability Use the Flyweight pattern when all of the following are true: An application uses a large number of object. Storage costs are high. Application-aware object state can be made extrinsic. Many groups of objects can be replaced by a few shared objects once extrinsic state is removed. The application doesn t depend on object identity. Design Patterns Flyweight [GoF] 3

Structure FlyweightFactory <<create>> Flyweight getflyweight(key) method(extrinsicstate) if (flyweight[key] exists) { return exisiting flyweight; else { create new flyweight; add it to pool; return it ConcreteFlyweight intrinsicstate method(extrinsicstate) UnsharedFlyweight allstate method(extrinsicstate) <<get>> Client <<use>> Design Patterns Flyweight [GoF] 4

Participants Flyweight (AbstractIcon) declares an interface through which clients act on any kind of flyweights protects against access by objects other than the Originator has effectively two interfaces: a narrow interface for Caretaker, and a wide interface for Originator ConcreteFlyweight (FolderIcon) implements the Flyweight interface, adds intrinsic state (if any) must be sharable, i.e., its intrinsic state must be independent of the flyweight s context UnsharedFlyweight (...) not all Flyweight subclasses must be shared. The Flyweight interface enables sharing; it doesn t enforce it FlyweightFactory (IconFactory) creates and pools flyweight objects ensures that flyweights are shared properly Client (Pane) maintains a reference to flyweight(s) computes or stores the extrinsic state of flyweight(s) Design Patterns Flyweight [GoF] 5

Collaborations Flyweight state is separated into intrinsic and extrinsic state. Intrinsic state is stored in the flyweight; extrinsic state is stored or computed in the client objects. Clients pass the extrinsic state to the flyweight when they invoke its methods. Clients must not instantiate Flyweights directly. Clients must obtain Flyweights exclusively from FlyweightFactory objects to ensure that they are shared properly. Consequences Flyweights may introduce run-time costs because of the finding, computing, and transferring of extrinsic state of Flyweight objects. These costs are offset by space savings which is a function of several factors: the reduction of the total number of instances that comes from sharing the amount of intrinsic state per object whether extrinsic state is computed or stored Design Patterns Flyweight [GoF] 6

Implementation Consider the following issues: Managing share objects. Because objects are share, clients should not instantiate them directly. Use a factory instead. Factory method. There are two approaches to consider when implementing the factory: Use a separate factory method for each kind of Flyweight object you create: // FlyweightFactory: public Flyweight createconcreteflyweight1() {... public Flyweight createconcreteflyweight2() {...... Use a generic factory method, parameterized with a key to distinguish the kind of Flyweight to create and return: // Alternative FlyweightFactory: public Flyweight createflyweight(string key) {... Design Patterns Flyweight [GoF] 7

Sample Code Let s consider a sketch of the code of the example in the Motivation section. A base class for icons of the application might look like: public abstract class AbstractIcon { public abstract void draw(graphics g, int tx, int ty, String name, boolean selected); Notice that we could have used a Java interface here. Notice also the variables denoting the extrinsic state. A concrete icon subclass stores its intrinsic state, and implements the draw method. In the example given here, there is also a distinction whether the icon is selected or not: public class FolderIcon extends AbstractIcon { private final int H = 48; private ImageIcon iconsel, iconunsel;... Design Patterns Flyweight [GoF] 8

The constructor s access should be made restricted. We make it package-visible here preventing clients not being in this package to directly create instances: // in class FolderIcon; FolderIcon() { URL iconurl = ClassLoader.getSystemResource("images/folder_o.png"); if (iconurl!= null) { iconsel = new ImageIcon(iconURL); else... // some kind or error handling iconurl = ClassLoader.getSystemResource("images/folder.png"); if (iconurl!= null) { iconunsel = new ImageIcon(iconURL); else... // some kind or error handling Next, we have to implement all the methods the flyweights support, given the extrinsic state. In our example, the only method is method draw: Design Patterns Flyweight [GoF] 9

// in class FolderIcon; public void draw(graphics g, int tx, int ty, String name, boolean sel) { // Clear the space occupied by either of the icons... if (sel) { iconsel.painticon(null, g, tx, ty); else { iconunsel.painticon(null, g, tx, ty); g.drawstring(name, tx, ty + H + 15); //title A factory class for the creation of the concrete flyweight icon objects might look like: public class IconFactory { private Map iconmap = new HashMap(); // Typically a Singleton, Singleton code not shown:... Design Patterns Flyweight [GoF] 10

The factory class in this example has one method to create any one of the icon objects it supports: // in class IconFactory: public AbstractIcon createicon(string key) { AbstractIcon icon = (AbstractIcon) iconmap.get(key); if (icon == null) { icon = makeicon(key); iconmap.put(key, icon); return icon; The private helper method makeicon actually create the application s icons: // in class IconFactory: private static AbstractIcon makeicon(string key) { AbstractIcon icon = null; if (key.equals("dir")) { icon = new FolderIcon(); else if (key.equals("java")) {... else icon = new UnknownIcon(); return icon; Design Patterns Flyweight [GoF] 11

A client uses the flyweights via the factory class. For example: // Client code, excerpt: // helper class: private class Item { String type; String name; AbstractIcon icon; Item(String type, String name, AbstractIcon icon) { this.type = type; this.name = name; this.icon = icon; In a client, application icons can then be created: // icon creation: IconFacory factory = IconFactory.getInstance(); Item item1 = new Item("dir","Folder1", factory.createicon("dir"));... Design Patterns Flyweight [GoF] 12

In the client, the icons can then be displayed: Related Patterns // draw the icon: Graphics g =...; // for each icon to draw: Item item =...; boolean selected =...; xpos =...; // calculate the X position ypos =...; // calculate the Y position item.icon.draw(g, xpos, ypos, item.name, selected); Flyweights are often combined with the Composite pattern. State and Strategy patterns can sometimes be implemented as flyweights. Design Patterns Flyweight [GoF] 13