Tecniche di Progettazione: Design Patterns

Similar documents
Tecniche di Progettazione: Design Patterns

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

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

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

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

- 2 - Companion Web Site. Back Cover. Synopsis

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

The system design must obey these constraints. The system is to have the minimum cost (capital plus operating) while meeting the constraints.

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

Unchained Malady A Tangle of Times

Provably Secure Camouflaging Strategy for IC Protection

Application of Bayesian Networks to Shopping Assistance

The Safety Case. Structure of Safety Cases Safety Argument Notation

The Safety Case. The safety case

An STPA Tool. Dajiang Suo, John Thomas

An Architectural Approach for Improving Availability in Web Services

CS 112 Introduction to Programming

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

Graphical User Interface in Java Using JavaFX

By far the majority of New Zealand s fisheries are performing well

G53CLP Constraint Logic Programming

If you need to reinstall FastBreak Pro you will need to do a complete reinstallation and then install the update.

PREAMBLE. Why the Informatics Olympiad in Team were born

Better Search Improved Uninformed Search CIS 32

Designing Objects with a Single Responsibility. Andrew P. Black

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

Breaking Up is Hard to Do: An Investigation of Decomposition for Assume-Guarantee Reasoning

Preparing Questions for Brownstone's Software Formats:

The Evolution of Transport Planning

Real-Time & Embedded Systems

Assignment A7 BREAKOUT CS1110 Fall 2011 Due Sat 3 December 1

A Novel Decode-Aware Compression Technique for Improved Compression and Decompression

Spreading Activation in Soar: An Update

On street parking manoeuvres and their effects on design

International olympiads in Informatics in Kazakhstan. A. Iglikov Z. Gamezardashvili B. Matkarimov

GOLOMB Compression Technique For FPGA Configuration

DESIGN AND ANALYSIS OF ALGORITHMS (DAA 2017)

CS472 Foundations of Artificial Intelligence. Final Exam December 19, :30pm

Decision Trees. an Introduction

Lab 3 Introduction to Quantitative Analysis: Pumps and Measurements of Flow

Parsimonious Linear Fingerprinting for Time Series

Automatic Identification and Analysis of Basketball Plays: NBA On-Ball Screens

Assignment #3 Breakout!

#19 MONITORING AND PREDICTING PEDESTRIAN BEHAVIOR USING TRAFFIC CAMERAS

CMPUT680 - Winter 2001

PC-based systems ELOP II-NT

Reliable Real-Time Recognition of Motion Related Human Activities using MEMS Inertial Sensors

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

Generating None-Plans in Order to Find Plans 1

Hazard Operability Analysis

We release Mascot Server 2.6 at the end of last year. There have been a number of changes and improvements in the search engine and reports.

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

CodeWarrior Development Studio for Microcontrollers V10.X MISRA-C:2004 Compliance Exceptions for the HC(S)08, RS08, ColdFire, Kinetis and Power

Solving Problems by Searching chap3 1. Problem-Solving Agents

Based on a handout by Eric Roberts

TR Electronic Pressure Regulator. User s Manual

Tutorial for the. Total Vertical Uncertainty Analysis Tool in NaviModel3

Real World Search Problems. CS 331: Artificial Intelligence Uninformed Search. Simpler Search Problems. Example: Oregon. Search Problem Formulation

Cyrus Soccer 2D Simulation

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

Changes in speed and efficiency in the front crawl swimming technique at 100m track

Mechanical Design Patterns

Using MATLAB with CANoe

CRICKET ONTOLOGY. Project Description :- Instructor :- Prof: Navjyothi Singh

Introduction to Interprocess Communication. Introduction to Interprocess Communication

By far the majority of New Zealand s fisheries are performing well

CENG 466 Artificial Intelligence. Lecture 4 Solving Problems by Searching (II)

INTRODUCTION P. 3 THE TEE P. 4 THE TEXT P. 7 THE GRAPHICS P. 9 THE LAYOUT P. 11 THE END P. 16

BRIEFING NOTES FOR TIMEKEEPER. Candidate Name.

Distributed Control Systems

Cuneiform. A Functional Workflow Language Implementation in Erlang. Jörgen Brandt Humboldt-Universität zu Berlin

Assignment 3: Breakout!

UNIVERSITY OF WATERLOO

POKEMON HACKS. Jodie Ashford Josh Baggott Chloe Barnes Jordan bird

Robust Task Execution: Procedural and Model-based. Outline. Desiderata: Robust Task-level Execution

The Future of Hydraulic Control in Water-Systems

Auto-Zero Calibration Technique for Pressure Sensors

DATA MINING ON CRICKET DATA SET FOR PREDICTING THE RESULTS. Sushant Murdeshwar

Spacecraft Simulation Tool. Debbie Clancy JHU/APL

Reduction of Bitstream Transfer Time in FPGA

HS2 Ltd HS2 London to West Midlands Route Corridor Reviews Journey Time Analysis. January 2012

CGG Maritime Exposure

Oxygen Meter User Manual

Control of Salinity in the Fish Tank ME 121. Tank Pump Sensor. Figure 1 Schematic of flow loop and salinity control scheme for the fish tank.

Adiabatic Compensation for Digiquartz Intelligent Transmitters

Transposition Table, History Heuristic, and other Search Enhancements

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

IDENTITY GUIDE Elizabethtown College. All rights reserved.

2017 IIHF BID REGULATIONS

Aryeh Rappaport Avinoam Meir. Schedule automation

Along-string pressure, temperature measurements hold revolutionary promise for downhole management

INTRODUCTION AND METHODS OF CMAP SOFTWARE BY IPC-ENG

Proposed. City of Grand Junction Complete Streets Policy. Exhibit 10

CONTROL VALVE TESTING

TOURO LAW CENTER S 1 st ANNUAL NATIONAL MOOT COURT COMPETITION: LAW AND RELIGION. April 10-11, COMPETITION RULES

Walking up Scenic Hills: Towards a GIS Based Typology of Crowd Sourced Walking Routes

2019 Formula SAE Japan Local Rules Number 2 Issued: January 18, 2019

Uninformed search methods

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

Transcription:

Tecniche di Progettazione: Design Patterns GoF: Flyweight 1

2

Flyweight Pattern Intent Use sharing to support large numbers of fine-grained objects efficiently Motivation Can be used when an application could benefit from using objects throughout their design, but a naïve implementation would be prohibitively expensive Objects for each character in a document editor Cost is too great! Can use flyweight to share characters

Example Flyweight 4

Head first example Flyweight The manager is acting as a collecion more than a Flyweight 5

Intrinsic vs. Extrinsic Most objects would share a set of stateless information, this could be extracted from the main objects to be held in flyweight objects Intrinsic The intrinsic data is held in the properties of the flyweight objects that are shared. This information is stateless and generally remains unchanged, as any changes would be effectively replicated amongst all of the objects that reference the flyweight Extrinsic Extrinsic data can be stateful as it is held outside of a flyweight object. It can be passed to methods of a flyweight when needed but should never be stored within a shared flyweight object.

GoF Example Creating a flyweight for each letter of the alphabet: Intrinsic state: a character code Extrinsic state: coordinate position in the document typographic style (font, color) is determined from the text layout algorithms and formatting commands in effect wherever the character appears 7

Flyweight: Structure

Flyweight: Participants Flyweight Declares an interface through which flyweights can receive and act on extrinsic state ConcreteFlyweight Implements the Flyweight interface and adds storage for intrinsic state, if any Must be shareable UnsharedConcreteFlyweight Although the flyweight design pattern enables sharing of information, it is possible to create instances of concrete flyweight classes that are not shared. In these cases, the objects may be stateful.

Flyweight: Participants FlyweightFactory Creates and manages flyweight objects Ensures that flyweights are shared properly Client Maintains reference to flyweights Computes or stores the extrinsic state of flyweights

Example 11

Flyweight object interface interface ICoffee { } public void servecoffee(coffeecontext context); 12

Concrete Flyweight object class Coffee implements ICoffee { private final String flavor; public Coffee(String newflavor) { } this.flavor = newflavor; System.out.println("Coffee is created! - " + flavor); public String getflavor() { return this.flavor; } public void servecoffee(coffeecontext context) { }} System.out.println("Serving " + flavor + " to table " + context.gettable()); 13

A context, here is table number class CoffeeContext { private final int tablenumber; public CoffeeContext(int tablenumber) { } this.tablenumber = tablenumber; public int gettable() { return this.tablenumber; } } 14

Flyweight Factory class CoffeeFactory { private HashMap<String, Coffee> flavors = new HashMap<String, Coffee>(); } public Coffee getcoffeeflavor(string flavorname) { Coffee flavor = flavors.get(flavorname); if (flavor == null) { flavor = new Coffee(flavorName); flavors.put(flavorname, flavor); } return flavor; } public int gettotalcoffeeflavorsmade() { return flavors.size(); } 15

Waitress (continues) public class Waitress { //coffee array private static Coffee[] coffees = new Coffee[20]; //table array private static CoffeeContext[] tables = new CoffeeContext[20]; private static int orderscount = 0; private static CoffeeFactory coffeefactory; public static void takeorder(string flavorin, int table) { coffees[orderscount] = coffeefactory.getcoffeeflavor(flavorin); tables[orderscount] = new CoffeeContext(table); orderscount++; } 16

Waitress (continued) public static void main(string[] args) { coffeefactory = new CoffeeFactory(); takeorder("cappuccino", 2); takeorder("cappuccino", 2); takeorder("regular Coffee", 1); takeorder("regular Coffee", 2); takeorder("regular Coffee", 3); for (int i = 0; i < orderscount; ++i) { coffees[i].servecoffee(tables[i]); } } } System.out.println("\nTotal Coffee objects made: " + coffeefactory.gettotalcoffeeflavorsmade()); 17

Flyweight: Applicability Use the Flyweight pattern when ALL of the following are true An application uses a large number of objects Storage costs are high because of the sheer quantity of objects Most object state can be made intrinsic Many Groups of objects may be replaced by relatively few shared objects once extrinsic state is removed The application doesn t depend on object identity

Flyweight: Consequences May introduce run-time costs associated with transferring, finding, and/or computing extrinsic state Costs are offset by space savings Storage savings are a function of the following factors: The reduction in the total number of instances that comes from sharing The amount of intrinsic state per object Whether extrinsic state is computed or stored Ideal situation High number of shared flyweights Objects use substantial quantities of both intrinsic and extrinsic state Extrinsic state is computed

Implementation Removing extrinsic state Success of pattern depends on ability to remove extrinsic state from shared objects No help if there are many different kinds of extrinsic state Ideally, state is computed separately Managing shared objects Objects are shared so clients should not instantiate FlyweightFactory is used to create and share objects Garbage collection may not be necessary

Java Strings Java Strings are flyweighted by the compiler wherever possible. Can be flyweighted at runtime with the intern method. public class StringTest { public static void main(string[] args) { String fly = "fly", weight = "weight"; String fly2 = "fly", weight2 = "weight"; System.out.println(fly == fly2); // true System.out.println(weight == weight2); // true String append = fly + weight; System.out.println(append == "flyweight"); // false String flyweight = (fly + weight).intern(); System.out.println(flyweight== "flyweight"); // true 21

Flyweight: Related Patterns Composite Often combined with flyweight Provides a logically hierarchical structure in terms of a directed-acyclic graph with shared leaf nodes State and Strategy Can be implemented as flyweights Used in game programming Ex reference http://gameprogrammingpatterns.com/

Ethimology Flyweight is a boxing category, for light weight people. Flyweight pattern is for "light weight" objects (though many of them). 23

Flyweight: homework In Flyweight pattern, a Flyweight object has intrinsic state that cannot be changed. This also means that a Flyweight object cannot have any public-accessible set() method to set a new value for some instance variable of the object. Consider using the Flyweight pattern to allow a Flyweight object to have set() methods. When a set() method of a Flyweight object is called, the object becomes a non-flyweight, non-shared object. This idea is similar to copy-on-write. Build an example of copy-on-write. For instance: decorate the Christmas tree and then change colour to some decorations 24