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.

Slides:



Advertisements
Similar presentations
Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup
Advertisements

Chapter 6 Advanced Function Features Pass by Value Pass by Reference Const parameters Overloaded functions.
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
PASSING PARAMETERS 1. 2 Parameter Passing (by Value) Parameters Formal Parameters – parameters listed in the header of the function Variables used within.
Matt Klein. Decorator Pattern  Intent  Attach Additional responsibilities to an object by dynamically. Decorators provide a flexible alternative to.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Flyweight: Structural Pattern Prepared by Galina Walters.
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.
Flyweight An Object Structural Design Pattern JM Imbrescia.
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.
Pointers. COMP104 Pointers / Slide 2 Pointers * A pointer is a variable used for storing the address of a memory cell. * We can use the pointer to reference.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Algorithm Programming Structural Design Patterns Bar-Ilan University תשס " ו by Moshe Fresko.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Behavioral Patterns C h a p t e r 5 – P a g e 128 BehavioralPatterns Design patterns that identify and realize common interactions between objects Chain.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
Functions Pass by Reference Alina Solovyova-Vincent Department of Computer Science & Engineering University of Nevada, Reno Fall 2005.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
CPSC 252 Concrete Data Types Page 1 Overview of Concrete Data Types There are two kinds of data types: Simple (or atomic) – represents a single data item.
C++ Review (3) Structs, Classes, Data Abstraction.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
1 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing:
Computing IV Singleton Pattern Xinwen Fu.
Parameter Passing Mechanisms Reference Parameters § §
Structural Pattern: Bridge When the abstract interface and the concrete implementation have been set up as parallel class hierarchies, it becomes difficult.
Behavioral Pattern: Strategy C h a p t e r 5 – P a g e 205 The Open-Closed Principle advocates designing software in such a way that it will absorb new.
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.
Team 6 “The Unparseables” Design Patterns Chain of Responsibility Observer Flyweight 1.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Creational Pattern: Factory Method At times, a framework is needed to standardize the behavior of objects that are used in a range of applications, while.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Variables and Data Types.  Variable: Portion of memory for storing a determined value.  Could be numerical, could be character or sequence of characters.
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.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Creational Pattern: Builder When a complex object needs to be created, it is sometimes beneficial to separate the construction of the object from its.
The This Pointer Programming in C++ Fall 2008 Dr. David A. Gaitros
Variables and memory addresses
The Flyweight Pattern (Structural) ©SoftMoore ConsultingSlide 1.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
1 Introduction to Object Oriented Programming Chapter 10.
Behavioral Pattern: Mediator C h a p t e r 5 – P a g e 169 When a program is made up of several classes, the logic and computation is divided among these.
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
1 Data Structures CSCI 132, Spring 2014 Lecture 2 Classes and Abstract Data Types Read Ch Read Style Guide (see course webpage)
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
Motivation for Generic Programming in C++
Software Design and Architecture
Review: Two Programming Paradigms
Flyweight Design Pattern
Student Book An Introduction
Classes and Data Abstraction
Flyweight Pattern 1.
Pointers and dynamic objects
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

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 r 4 – P a g e 109 However, when very large numbers of such objects are needed in an application, this level of granularity can be prohibitively expensive in terms of performance and memory usage. The Flyweight Pattern tackles this problem by splitting the objects into their extrinsic (i.e., state-dependent) and intrinsic (state-independent) components. The intrinsic parts are shared within the Flyweight object, while the extrinsic parts are controlled by the client and passed to the Flyweight as needed.

The Flyweight Pattern C h a p t e r 4 – P a g e 110 The Client maintains a reference to the Flyweight objects and computes or stores their extrinsic state. The FlyweightFactory creates and manages the Flyweight objects, ensuring proper sharing (i.e., if a client needs a Flyweight, the FlyweightFactory supplies an existing one or, if none exists, creates a new one). The Flyweight declares an interface through which the concrete Flyweight objects can deal with their extrinsic state. The ConcreteFlyweight implements the Flyweight interface and adds storage for its intrinsic state; although the Flyweight interface enables sharing, UnsharedConcreteFlyweight objects may exist.

Non-Software Flyweight Example The public switched telephone network is an example of a Flyweight. C h a p t e r 4 – P a g e 111 There are several resources (ConcreteFlyweights) such as dial tone generators, ringing generators, and digit receivers that must be shared between all subscribers. A subscriber (the Client) is unaware of how many resources are in the pool when he or she lifts the handset to make a call. All that matters to subscribers is that a dial tone is provided, digits are received, and the call is completed.

C++ Flyweight Pattern Example C h a p t e r 4 – P a g e 112 /* Network links are the Flyweight objects here, with the technology type being used (e.g., */ /* MPLS, BGP) as their intrinsic features and their adjacent nodes (types include core routers, */ /* provider-edge routers, and subscriber-edge routers), adjacent interfaces (types include IP, */ /* ATM, etc.), and IP address ranges as their extrinsic features. */ /* */ /* When each link in the network is capable of supporting several IP addresss, specific IP */ /* addresses must be assigned to the interfaces supported by the links between adjacent nodes, */ /* which, for elaborate networks, can become a prohibitive task. */ #include #include "RealLink.h" using namespace std; void main() { GenericLinkContext* aLinkContext = new GenericLinkContext(); RealLink* aLink = new RealLink("MPLS", "Core Router A", "Core Router B", "Interface IP", "Interface ATM", aLinkContext); RealLink* anotherLink = new RealLink("BGP", "Core Router X", "Edge Router Y", "Interface ATM", "Interface IP", aLinkContext); aLinkContext->SetAddressRange(anotherLink->mySlotNumber, " x", 6, 9); aLinkContext->SetAddressRange(aLink->mySlotNumber, " x", 0, 7); cout GetTechnologyType() << " link, the IP Address range is " GetAllIPAddresses() << endl << endl; cout GetTechnologyType() << " link, the IP Address range is " GetAllIPAddresses() << endl << endl; }

C h a p t e r 4 – P a g e 113 #include using namespace std; class GenericLinkContext { public: explicit GenericLinkContext() { SetNextFreeSlot(-1); } virtual ~GenericLinkContext() {} virtual int GetNextFreeSlot() { if (nextFreeSlot < MAX_ARRAY_LENGTH) return ++nextFreeSlot; else return nextFreeSlot; } virtual void SetNextFreeSlot(int theNextFreeSlot) { nextFreeSlot = theNextFreeSlot; } virtual void SetAddressRange(int slot, string baseAddress, int offset, int range) { AddressRangeArray[slot].baseRangeAddress = baseAddress; AddressRangeArray[slot].addressOffset = offset; AddressRangeArray[slot].addressRange = range; } virtual string GetBaseAddress(int slot) { return AddressRangeArray[slot].baseRangeAddress; } virtual int GetAddressOffset(int slot) { return AddressRangeArray[slot].addressOffset; } virtual int GetAddressRange(int slot) { return AddressRangeArray[slot].addressRange; } private: int nextFreeSlot; static const int MAX_ARRAY_LENGTH = 10; /* Each entry in the array AddressRangeArray stores the IP address range details */ /* for a given link. Each link has an associated slot in this array. So when a new */ /* link must be created with a specific IP address range, the nextFreeSlot value */ /* is retrieved by invoking GetNextFreeSlot(). If the value is less than the */ /* maximum (10), a new address range array slot will be allocated. Once this new */ /* slot is obtained, the IP address range can be supplied via SetAddressRange(). */ struct AddressRanges { string baseRangeAddress; int addressOffset; int addressRange; } AddressRangeArray[MAX_ARRAY_LENGTH]; };

C h a p t e r 4 – P a g e 114 #include "GenericLinkContext.h" #include using namespace std; class GenericLink { public: explicit GenericLink(GenericLinkContext* aLinkContext, string nodeA, string nodeB, string ifA, string ifB) { linkContext = aLinkContext; mySlotNumber = linkContext->GetNextFreeSlot(); NodeA = nodeA; NodeB = nodeB; InterfaceA = ifA; InterfaceB = ifB; } virtual ~GenericLink() {} protected: GenericLinkContext* linkContext; public: int mySlotNumber; private: string NodeA; string NodeB; string InterfaceA; // Each interface can support many IP addresses string InterfaceB; // Each interface can support many IP addresses };

C h a p t e r 4 – P a g e 115 #include "GenericLink.h" #include using namespace std; class RealLink : public GenericLink { public: explicit RealLink(string aTechnologyType, string nodeA, string nodeB, string ifA, string ifB, GenericLinkContext* aLinkContext): GenericLink(aLinkContext, nodeA, nodeB, ifA, ifB) { technologyType = aTechnologyType; } virtual ~RealLink() {} string GetAllIPAddresses() { string ipAddressRange = ""; int addressOffset = linkContext->GetAddressOffset(mySlotNumber); int addressRange = linkContext->GetAddressRange(mySlotNumber); ipAddressRange = ipAddressRange + linkContext->GetBaseAddress(mySlotNumber) + " - " + linkContext->GetBaseAddress(mySlotNumber); int index = 0; while (ipAddressRange[index] != 'x') index++; ipAddressRange[index] = addressOffset + '0'; while (ipAddressRange[index] != 'x') index++; ipAddressRange[index] = addressRange + '0'; return ipAddressRange; } string GetTechnologyType() { return technologyType; } private: string technologyType; };

Flyweight Pattern Advantages C h a p t e r 4 – P a g e 116 There are cases in programming where it seems that a very large number of small class instances is needed to represent data. Essentially, the variables that differ can be moved outside of the class instance and passed in as part of a method call. If the instances are fundamentally the same except for a few parameters, the number of instantiations can be greatly reduced by means of the Flyweight Pattern. While the Flyweight Pattern is not commonly used in application software, it does provide a useful technique for managing resources at the system level.