Imagine that you need to create a system to represent all of the cars in a city. You need to store the details about each car ( model, and year) and the.

Slides:



Advertisements
Similar presentations
GoF State Pattern Aaron Jacobs State(305) Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
Advertisements

CS 350 – Software Design The Bridge Pattern – Chapter 10 Most powerful pattern so far. Gang of Four Definition: Decouple an abstraction from its implementation.
Structural Pattern: Flyweight To maximize flexibility, it is often advantageous to model objects down to very fine levels of granularity. C h a p t e.
Matt Klein. Decorator Pattern  Intent  Attach Additional responsibilities to an object by dynamically. Decorators provide a flexible alternative to.
Flyweight: Structural Pattern Prepared by Galina Walters.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
 The position of a method in a program is not critical.  Why?
Flyweight An Object Structural Design Pattern JM Imbrescia.
Prototype Pattern Creational Pattern Specify the kinds of objects to create using a prototypical instance, and create new objects by copy this prototype.
Design Patterns I 1. Creational Pattern Singleton: intent and structure Ensure a class has one instance, and provide a global point of access to it 2.
Algorithm Programming Structural Design Patterns Bar-Ilan University תשס " ו by Moshe Fresko.
Software Design and Documentation Individual Presentation: Composite Pattern 9/11/03.
Katie C. O’Shea Dennis T. Tillman 11 February 2K2 Flyweight.
Design patterns. What is a design pattern? Christopher Alexander: «The pattern describes a problem which again and again occurs in the work, as well as.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Tot 15 LTPDA Graphic User Interface summary and status N. Tateo 26/06/2007.
In the name of Allah The Proxy Pattern Elham moazzen.
Pattern Hatching - John Vlissides Pages 85 – 101 Todd Anderson
Strategy Design Patterns CS 590L - Sushil Puradkar.
Views Lesson 7.
Computing IV Singleton Pattern Xinwen Fu.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
GoF: Document Editor Example Rebecca Miller-Webster.
Patterns COM379 University of Sunderland James Malone.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
Structural Design Patterns
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns V More Structural Patterns.
02 - Structural Design Patterns – 2 Moshe Fresko Bar-Ilan University תשס"ח 2008.
Factory Method Explained. Intent  Define an interface for creating an object, but let subclasses decide which class to instantiate.  Factory Method.
Design Patterns Yonglei Tao. Design Patterns  A design pattern describes a recurring design problem, a solution, and the context in which that solution.
Prototype pattern Participants Prototype (Graphic) – declared an interface for cloning itself ConcretePrototype (EditBox, Slider) – implements an operation.
CSE 332: Design Patterns Review: Design Pattern Structure A design pattern has a name –So when someone says “Adapter” you know what they mean –So you can.
Proxy, Observer, Symbolic Links Rebecca Chernoff.
08 - StructuralCSC4071 Structural Patterns concerned with how classes and objects are composed to form larger structures –Adapter interface converter Bridge.
Structural Patterns1 Nour El Kadri SEG 3202 Software Design and Architecture Notes based on U of T Design Patterns class.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Strategy Pattern.
DESIGN PATTERNS COMMONLY USED PATTERNS What is a design pattern ? Defining certain rules to tackle a particular kind of problem in software development.
Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams.
Billy Bennett June 22,  Intent Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
Design Patterns Introduction
STRATEGY PATTERN. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract.
The State Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Prototype Pattern (Creational) ©SoftMoore ConsultingSlide 1.
The Flyweight Pattern (Structural) ©SoftMoore ConsultingSlide 1.
Singleton Pattern Presented By:- Navaneet Kumar ise
The Singleton Pattern (Creational)
SOCSAMS e-learning Dept. of Computer Applications, MES College Marampally FILE SYSTEM.
The const Keyword Extreme Encapsulation. Humble Beginnings There are often cases in coding where it is helpful to use a const variable in a method or.
The Memento Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
PROTOTYPE. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract factory.
Design Patterns Creational Patterns. Abstract the instantiation process Help make the system independent of how its objects are created, composed and.
1 Lecture Material Design Patterns Visitor Client-Server Factory Singleton.
SQL IMPLEMENTATION & ADMINISTRATION Indexing & Views.
Examples (D. Schmidt et al)
Factory Patterns 1.
Creational Pattern: Prototype
Software Design and Architecture
Software Design and Architecture
Flyweight Design Pattern
Object Pool Pattern 1.
Decorator Intent Also known as Wrapper Example: a Text Window
LTPDA Graphic User Interface summary and status
Flyweight Pattern 1.
Introduction to Data Structure
Defining Classes and Methods
Software Design Lecture : 39.
Presentation transcript:

Imagine that you need to create a system to represent all of the cars in a city. You need to store the details about each car ( model, and year) and the details about each car’s ownership (owner name, tag number, last registration date). Flyweight Pattern  Example: Car Registrations /* Car class, un-optimized. */ class Car { public Car ( model, year, owner, tag, renewDate) { this.model = model; this.year = year; this.owner = owner; this.tag = tag; this.renewDate = renewDate; { // }

Flyweight Pattern  Intent Use sharing to support a large number of fine-grained objects efficiently. The Flyweight pattern describes how to share objects to allow their use at fine granularities without prohibitive storage cost  Motivation converting many independent objects into a few shared objects, reducing the amount of resources needed to run web applications The trick is to separate the intrinsic state from the extrinsic state of each object: - Extrinsic state: information that depends and varies with the flyweight's context ( thus shouldn't be shared ). This information should be stored outside the flyweight. - Intrinsic state: information that's independent of the flyweight's context. This information should be store inside the flyweight.

Flyweight Pattern  Structure Flyweight operation(extrinsicState) FlyweightFactory getFlyweight(key) Client ConcreteFlyweight operation(extrinsicState) intrinsicState UnsharedConcreteFlyweight operation(extrinsicState) allState if(flyweight(key) exists) { return existing flyweight; } else { create new flyweight; add it to pool of flyweights return the new flyweight; }.

Flyweight Pattern  Participants Flyweight : declares the interface that flyweights use to act on extrinsic state. ConcreteFlyweight : implements the flyweight and adds storage for the intrinsic state (which should be sharable). UnsharedConcreteFlyweight: not all flyweight need to be shared. Client: stores the extrinsic state of the flyweights. FlyweightFactory: creates and manages flyweight objects.ensures that flyweights are shared properly.

Flyweight Pattern  Collaborations |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| Client FlyweightFactory Flyweight getFlyweight() FlyweightFound= FindFlyweight() [! FlyweightFound] New() flyweight Operation (extrinsic state)

Categorizing an object’s data as intrinsic or extrinsic: the physical car data ( model, year) is intrinsic, and the owner data (owner name, tag number, last registration date) is extrinsic. This means that only one car object is needed for each combination of model, and year. Flyweight Pattern  Example: Car Registrations /* Car class, optimized as a flyweight. */ class Car { public Car ( model, year) { this.model = model; this.year = year; } // }

Instantiation Using a Factory: Factory ensures that only a single copy of each unique intrinsic state is created: Flyweight Pattern  Example: Car Registrations /* CarFactory singleton. */ class CarFactory { private Car createdCars []; public Car createCar( model, year) { // Check to see if this particular combination has been created // before. otherwise create a new instance and save it. if(! createdCars[ model + '-' + year]) { var car = new Car(model, year); createdCars[ model + '-' + year] = car; } return createdCars[model + '-' + year]; } // }

Extrinsic State Encapsulated in a Manager:All of the data that was removed from the Car objects has to be stored somewhere; you use a singleton as a manager to encapsulate that data. Flyweight Pattern  Example: Car Registrations /* CarRecordManager singleton. */ class CarRecordManager { private CarRecord carRecordDatabase []; // Add a new car record into the city's system. public void addCarRecord (model, year, owner, tag, renewDate) { car = CarFactory.createCar( model, year); carRecordDatabase[tag] = { owner: owner, renewDate: renewDate, car: car } // }

Flyweight Pattern  Applicability The Flyweight pattern's effectiveness depends heavily on how and where it's used. Flyweight should only be used when all the following are true: An application uses a large number of objects. Storage costs are high because of the sheer quantity of objects. At least some of the data stored within each of these objects must be able to be made extrinsic. Objects can be replaced by few shared objects once the extrinsic state is removed

Flyweight Pattern  Consequences By increasing the amount of data that is shared, we can increase our savings in space (memory, disk, etc). This saving is heavily influenced by the number of flyweight we need to create. However, the use of Flyweights may introduce some performance overhead. Since some data is stored outside the object, there are some performance penalties (retrieving that data).

Flyweight Pattern  Implementation Removing extrinsic state :The first step when building a flyweight is to decide what data should be intrinsic and what data should be extrinsic. This decision is critical since it will heavily influence the flyweight's performance. Managing shared objects: Because objects are shared, clients shouldn't instantiate them directly. FlyweightFactory lets clients locate a particular flyweight.

Flyweight Pattern  Example: Lexi case study Object Structure

Flyweight Pattern  Example: Lexi case study Object Sharing

Flyweight Pattern  Example: Lexi case study class Character : public Glyph { public: Character(char); virtual void Draw(Window*, GlyphContext&); private: char _charcode; }; class GlyphFactory { public: GlyphFactory(); virtual ~GlyphFactory(); virtual Character* CreateCharacter(char); virtual Row* CreateRow(); virtual Column* CreateColumn(); //... private: Character* _character[]; };

Flyweight Pattern  Example: Lexi case study class GlyphContext { public: GlyphContext(); virtual ~GlyphContext(); virtual void Next(int step = 1); virtual void Insert(int quantity = 1); virtual Font* GetFont(); virtual void SetFont(Font*, int span = 1); private: int _index; BTree* _fonts; }; Character* GlyphFactory::CreateCharacter (char c) { if (!_character[c]) { _character[c] = new Character(c); } return _character[c]; }

Flyweight Pattern  Example: Lexi case study BTree

Flyweight Pattern  Example: Lexi case study GlyphContext gc; Font* times12 = new Font("Times-Bold-12"); // gc.SetFont(times12, 42);

Suppose we want to draw a small folder icon with a name under it for each person in an organization. they are actually all the same graphical image. Even if we have two icons-one for "is Selected" and one for "not Selected“- the number of different icons is small. Flyweight Pattern  Example: Folder Objects

Flyweight Pattern  Example: Folder Objects class Folder{ public Folder(Color c){ color = c; } public void Draw(Graphics g, int tx, int ty, String name){ //draw folder } class FolderFactory{ Folder unSelected, Selected; public FolderFactory(){ Selected = new Folder(Color.brown); unSelected = new Folder(Color.yellow); { public Folder getFolder(boolean isSelected)} if (isSelected) return Selected; else return unSelected; {

Flyweight Pattern  Example: Folder Objects public void FolderFactory :: paint(Graphics g){ Folder f; String name; //go through all the names and folders for (int i = 0; i< names.size(); i++)} name = (String)names.elementAt(i); if(name.equals(selectedName)) f = fact.getFolder(true); else f = fact.getFolder(false); //have that folder draw itself at this spot f.Draw(g, x, row, name); // }