Factories, Builders and Singletons. Steven R. Bagley
|
|
- Irma Stafford
- 5 years ago
- Views:
Transcription
1 Factories, Builders and Singletons Steven R. Bagley
2 The Patterns So Far Behavioural Patterns Strategy Observer Structural Patterns Decorator
3 Introduction Object Creational Patterns Sometimes new isn t enough
4 new Object The new operator creates a new object of a particular class CFoo *pfoo = new CFoo(); Type of object fixed at compile time No way to change the type at run time Tied to a concrete implementation
5 Object Creation Interfaces let our code use objects without knowing what they are But to create objects they must know about concrete types Object creational patterns are about letting code create objects without knowing their concrete type
6 Object Creation Families of related objects e.g. UI toolkits All support a common interface Multiple implementations for different environments However code that uses them has to know about all types to create the correct type Patterns to abstract it away
7 Complex Objects Creation of objects can be complicated Decorator pattern for instance Might be produced based on input from a file (e.g. parsing an XML document)
8 How many? new can create multiple instances of a class Sometimes necessary to restrict the number of instances E.g. object represents a specific resource of which there is only one
9 Object Creation Object Creational Patterns Factory Singletons Builder
10 new not harmful These patterns augment new Don t replace it All the patterns will call new at some point Sometimes it makes sense to call new Other times it makes sense to abstract it
11 Diagrams Suppose we want to output diagrams from our application Model these diagrams internally as objects Objects represent common features (lines, rectangles, circles etc). Serialize the objects into the image format (e.g. PDF)
12 Diagram AddShape Serialize 1 * <<interface>> Shape SetPosition SetFill SetStroke Serialize Rectangle Text BezierCurve
13 void DrawDiagram() Diagram *diag = new Diagram(); Shape *tmp; tmp = new Rectangle(300,300); tmp->setposition(72,72); diag->addshape(tmp); tmp = new Text( Hello World, ); tmp->setposition(36,40); diag->addshape(tmp); /* */ diag->serialize( new.pdf );
14 Fixed Format Code fixed to PDF format To change the format, we need to change the code Change diagram objects to export another format Change generation code to create new objects
15 Late-bound Diagrams Output format decision made at runtime Interfaces for the objects (Diagram, Rectangle etc) Concrete Implementations for each format
16 <<interface>> Diagram AddShape Serialize <<interface>> Shape SetPosition SetFill SetStroke Serialize PDFDiagram SVGDiagram Rectangle Text BezierCurve PSDiagram PDFRectangle PSRectangle PDF BezierCurve PS BezierCurve SVGRectangle PDFText PSText SVG BezierCurve SVGText
17 Confusing code Implementing support for multiple formats is easy Using it however is not Every time we need to create an object, we need to check what type we should use
18 Diagram diag; switch(output) case SVG: diag = new SVGDiagram; break; case PSCRIPT: diag = new PSDiagram; break; default: diag = new PDFDiagram; break;
19 Encapsulate Code That s a lot of code to write every time Why not encapsulate it? Create a new class with methods to create each type of object Rather than create the objects directly call the methods on an instance of this class
20 class DiagramFactory public: DiagramFactory(int type); Diagram *CreateDiagram(); Rectangle *CreateRectangle( ); Text *CreateText( ); Bezier *CreateBezier( ); private: int m_output; ;
21 void DrawDiagram(DiagramFactory *f) Diagram diag = f->creatediagram(); Shape tmp; tmp = f->createrectangle(300,300); tmp->setposition(72,72); diag->addshape(tmp); tmp = f->createtext( Hello World, ); tmp->setposition(36,40); diag->addshape(tmp); /* */ diag->serialize( new.pdf );
22 Diagram *DiagramFactory::CreateDiagram() switch(m_output) case SVG: return new SVGDiagram; break; case PSCRIPT: return new PSDiagram; break; default: return new PDFDiagram; break;
23 Rectangle *DiagramFactory::CreateRectangle(int width, int height) switch(m_output) case SVG: return new SVGRectangle(width, height); break; case PSCRIPT: return new PSRectangle(width, height); break; default: return new PDFRectangle(width, height); break;
24 Proto-Factory Almost a Factory Our code is now completely isolated from any concrete objects Factory is a bit messy Lots of duplicated code checking which type of object to create Type fixed when factory created
25 Abstract Factory Abstract Factory pattern Define the Factory as an abstract interface Inherit from that concrete implementations for PDF, PostScript and SVG
26 <<interface>> DiagramFactory CreateDiagram CreateRectangle CreateText CreateBezierCurve PDFDiagramFactory PSDiagramFactory SVGDiagramFactory
27 Diagram *SVGDiagramFactory::CreateDiagram() return new SVGDiagram; Diagram *PDFDiagramFactory::CreateDiagram() return new PDFDiagram; Diagram *PSDiagramFactory::CreateDiagram() return new PSDiagram;
28 void DrawDiagram(DiagramFactory *f) Diagram diag = f->creatediagram(); Shape tmp; tmp = f->createrectangle(300,300); tmp->setposition(72,72); diag->addshape(tmp); tmp = f->createtext( Hello World, ); tmp->setposition(36,40); diag->addshape(tmp); /* */ diag->serialize( new.pdf );
29 Decisions Removed the conditionals from the code Yet the code still can output to different formats Decision is now in choosing what Factory Object to give DrawDiagram This is classic OO Design
30 Gained Extensibility DrawDiagram can output to any format Providing we have a sub-class of DiagramFactory that lets it create the objects Strive to write code like this!
31 Factory or Strategy? Isn t this just the Strategy pattern? Similar implementation, different reasons Strategy is provides behaviour Abstract Factory is about creating objects So different names
32 <<interface>> AbstractFactory CreateProduct <<interface>> AbstractProduct ConcreteFactory ConcreteProduct
33 Terminology Abstract Factory interface for creating Abstract Products Concrete Factory implements an Abstract Factory to create Concrete Products
34 Terminology Abstract Factory interface for creating Abstract Products Concrete Factory implements an Abstract Factory to create Concrete Products Client uses only Abstract Factory and Abstract Product
35 Other Factory Patterns The Abstract Factory not the only Factory Pattern Abstract Factory most often used when you need to create objects from multiple families of objects E.g. UI objects Used when lots of clients
36 Local Factories Sometimes it is only necessary to vary the objects created in a small context In these cases, creating a Factory Object is over the top Especially if we do not need to vary objects produced at runtime Let s look at another model
37 Pizza Store Imagine modelling the ordering process for an pizza store in OO form Pizzas represented by Objects Pizza objects control production line to create the pizza Base Pizza class with specializations Decorator would allow custom pizzas
38 Pizza Prepare() Bake() Cut() Box() CheesePizza HamPineapplePizza VeggiePizza PepperoniPizza
39 Pizza Store PizzaStore Object to control ordering of pizzas etc Has an OrderPizza method like the following:
40 Pizza *PizzaStore::OrderPizza(char *type) Pizza *pizza; if(0 == strcmp(type, cheese )) pizza = new CheesePizza(); else if(0 == strcmp(type, greek )) pizza = new GreekPizza(); else if(0 == strcmp(type, pepperoni )) pizza = new PepperoniPizza(); continued
41 pizza->prepare(); pizza->bake(); pizza->cut(); pizza->box(); return pizza;
42 Pizza ordering OrderPizza method creates the correct type of pizza to make Then performs tasks needed to order it Changing supported pizzas means changing OrderPizza Not closed for modification
43 Encapsulation We ve seen this before Encapsulate what varies Take out the creation bit and move it into a PizzaFactory OrderPizza calls the factory s create method to create the relevant pizza
44 Pizza *PizzaStore::OrderPizza(char *type) Pizza *pizza; PizzaFactory *pf = new PizzaFactory; pizza = pf->createpizza(type); pizza->prepare(); pizza->bake(); pizza->cut(); pizza->box(); return pizza;
45 Different Pizzas By changing the PizzaFactory, we can change the type of pizza Thin-crust Deep-pan So can create franchise stores specializing in different types by changing the factory object the store object uses
46 Quality Control Factory object lets anyone create objects Sometimes necessary to tie the creation into the algorithm more directly A franchise could use our PizzaFactory to implement it s own production line that doesn t use the cut() method
47 Factory Method Make the factory be a method rather than an object A Factory Method Make this method abstract (and private!) Subclass this object to implement factory method
48 Pizza Factory Method In terms of our Pizza Store Add an abstract CreatePizza method Alter OrderPizza to call this method rather than a Factory object
49 class PizzaStore public: Pizza *OrderPizza(char *type); private: virtual Pizza *CreatePizza(char *type) = 0; ;
50 Pizza *PizzaStore::OrderPizza(char *type) Pizza *pizza; pizza = CreatePizza(type); pizza->prepare(); pizza->bake(); pizza->cut(); pizza->box(); return pizza;
51 Using the PizzaStore Can t create a PizzaStore directly since not all its methods are implemented Need to create concrete subclasses that can be instantiated Subclass for each franchise
52 class NYPizzaStore : PizzaStore private: virtual Pizza *CreatePizza(char *type); ;
53 Pizza *NYPizzaStore::CreatePizza(char *type) Pizza *pizza; if(0 == strcmp(type, cheese )) pizza = new NYStyleCheesePizza(); else if(0 == strcmp(type, greek )) pizza = new NYStyleGreekPizza(); else if(0 == strcmp(type, pepperoni )) pizza = new NYStylePepperoniPizza(); return pizza;
54 class ChicagoPizzaStore : PizzaStore private: virtual Pizza *CreatePizza(char *type); ;
55 Pizza *ChicagoPizzaStore::CreatePizza(char *type) Pizza *pizza; if(0 == strcmp(type, cheese )) pizza = new ChicagoStyleCheesePizza(); else if(0 == strcmp(type, greek )) pizza = new ChicagoStyleGreekPizza(); else if(0 == strcmp(type, pepperoni )) pizza = new ChicagoStylePepperoniPizza(); return pizza;
56 How it works Create an instance of a franchise (e.g. NYPizzaStore) Call OrderPizza on this instance Implementation of OrderPizza from baseclass is called
57 Pizza *PizzaStore::OrderPizza(char *type) Pizza *pizza; pizza = CreatePizza(type); pizza->prepare(); pizza->bake(); pizza->cut(); pizza->box(); return pizza;
58 Pizza *PizzaStore::OrderPizza(char *type) Pizza *pizza; pizza = CreatePizza(type); pizza->prepare(); pizza->bake(); pizza->cut(); pizza->box(); return pizza;
59 Pizza *NYPizzaStore::CreatePizza(char *type) Pizza *pizza; if(0 == strcmp(type, cheese )) pizza = new NYStyleCheesePizza(); else if(0 == strcmp(type, greek )) pizza = new NYStyleGreekPizza(); else if(0 == strcmp(type, pepperoni )) pizza = new NYStylePepperoniPizza(); return pizza;
60 Pizza *PizzaStore::OrderPizza(char *type) Pizza *pizza; pizza = CreatePizza(type); pizza->prepare(); pizza->bake(); pizza->cut(); pizza->box(); return pizza;
61 Pizza *PizzaStore::OrderPizza(char *type) Pizza *pizza; pizza = CreatePizza(type); pizza->prepare(); pizza->bake(); pizza->cut(); pizza->box(); return pizza;
62 Factory Method Definition: The Factory Method defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to the subclasses.
63 Pizza *PizzaStore::OrderPizza(char *type) Pizza *pizza; pizza = CreatePizza(type); pizza->prepare(); pizza->bake(); pizza->cut(); pizza->box(); return pizza;
64 Design Principle Depend upon abstractions. Do not depend upon concrete classes
65 Dependency Inversion This is the Dependency Inversion Principle Similar to Program to an interface High-level components should not depend on low-level components Both should depend on abstractions
66 Dependency What the heck does this mean? An object depends on something when it relies on it to work This means that object may need to be modified if the thing it depends on changes Look at the original pre-factory Pizza store code
67 Pizza *PizzaStore::OrderPizza(char *type) Pizza *pizza; if(0 == strcmp(type, cheese )) pizza = new CheesePizza(); else if(0 == strcmp(type, greek )) pizza = new GreekPizza(); else if(0 == strcmp(type, pepperoni )) pizza = new PepperoniPizza(); continued
68 Pizza Dependency PizzaStore depends on all the different types of Pizza Even though it uses a Pizza interface It still instantiates the concrete objects So it depends on their implementation E.g. if the constructor changes
69 Pizza Dependency PizzaStore is a high-level component Objects that depend on other objects are called high-level components Their behaviour is defined in terms of other components
70 Pizza *PizzaStore::OrderPizza(char *type) Pizza *pizza; pizza = CreatePizza(type); pizza->prepare(); pizza->bake(); pizza->cut(); pizza->box(); return pizza;
71 PizzaStore high-level component CheesePizza GreekPizza PepperoniPizza low-level components
72 Dependency PizzaStore is a high-level component Pizzas are low-level components PizzaStore depends on concrete Pizzas
73 Independent Pizzastore PizzaStore is written in terms of Pizza interface Because it instantiates the concrete objects directly, it s still dependent on them Factory Method makes PizzaStore independent of the objects It now relies on an abstraction
74 PizzaStore Pizza CheesePizza GreekPizza PepperoniPizza Everything is now dependent on Pizza
75 Dependent Subclasses Because the CreatePizza method isn t implemented PizzaStore is independent of all concrete pizzas We create sub-classes which are dependent on the concrete pizzas
76 Inversion? So where does the inversion bit come in? We invert our way of thinking about the dependency Normally, we think about the high-level components and then the lower level ones it uses Start with abstractions and work out
77 Thinking about Pizza Need to implement a PizzaStore, what do we need? Started at the top and worked down to concrete classes Invert the thinking, start at the bottom and work up Pizza, better have classes for the different types: CheesePizza, VeggiePizza, etc All these pizzas are just pizza, need a Pizza type
78 Inverted Pizzas Thinking about Abstractions, now think about the Pizza store Close, but don t forget to create a factory to create the concrete classes otherwise you are dependent Can design Pizza Store around the abstraction and not worry about the concrete classes
79 Tips for Dependency Inversion No variable should hold a reference to a concrete class No class should derive from a concrete class No method should override an implemented method of any of its base classes
80 Tips for Dependency Inversion No variable should hold a reference to a concrete class No class should derive from a concrete class THESE ARE, No method should override an implemented method of any of its base classes OF COURSE, IMPOSSIBLE!
81 Guidelines The Dependency Inversion Principle is a guideline not a rule Know why you are breaking it If the class isn t likely to change then it isn t a problem (e.g. Java String class) If it is, think careful about whether you d be better to use a Factory Method
82 Which Factory? Factory Method Specializing a class to use a particular set of objects Abstract Factory Change objects created at runtime Lots of users (e.g. UI Toolkit abstraction)
83 Singleton Pattern
84 Controlling Creation By default, object creation is not under the control of the class being created new lets client creates any number of instances But what if we need to restrict the number of objects?
85 Application Preferences Suppose we have an object that handles our application preferences Handles storing them on disk Provides a programatic interface to access the preferences Dangerous to have more than one instance of it
86 Singleton Objects Need to ensure one and only instance is ever created Need to provide a way for the code to find that instance
87 Finding Single instances Global Variables Static Class Variables Forces objects to know about implementation details When does the object get created exactly?
88 Think Factory Factory Methods let us abstract away creation of objects Same technique for handling singletons Usually a static method Clients get the singleton object by calling the method
89 SingletonObject *gpobj = NULL; SingletonObject *GetSingleton() if(null == gpobj) gpobj = new SingletonObject(); return gpobj; Still got a global or static variable to store the pointer to the instance, but the client isn t aware of it
90 Multiple Objects Previous code provides an interface to one and only one instance of a class But clients could still call new to create other instances How do we stop this? Let s look in detail at the constructor
91 class CPotentialSingleton public: CPotentialSingleton(); /* */ ; When we define the constructor we define it as being publically accessible
92 Private Constructors Constructors can be declared public, private or protected Public anything can create them Private only this class can create them Protected only this or subclasses can create them Make the singleton constructor private
93 class CPotentialSingleton private: CPotentialSingleton(); public: /* */ ; Only thing that can create these objects, are other things of the same class
94 Private Construction How do we now instantiate the singleton? Static (class) methods can call private methods on objects Including private constructors If we make GetSingleton() a static method then it can create the single object
95 public GetSingleton method to get the shared instance class CSingleton private: CSingleton(); static CSingleton *s_singleinstance; public: static CSingleton *GetSingleton(); /* */ ; private static variable rather than global now (for neatness mainly) to store instance
96 CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) s_singleinstance = new CSingleton(); return s_singleinstance;
97 Singleton Pattern That s the implementation of the singleton pattern Private constructor stops objects instantiated Static method enables the class to control the creation and return of objects
98 Singleton Pattern Definition: The Singleton Pattern ensures a class has only one instance and provides a global point of access to it.
99 Singleton Problem The classic Singleton implementation has a fatal flaw It is not thread-safe It is possible for more than one instance of the singleton to be created Depending on where a context-switch might happen
100 CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) s_singleinstance = new CSingleton(); return s_singleinstance; gpobj
101 CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) s_singleinstance = new CSingleton(); return s_singleinstance; gpobj
102 CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) s_singleinstance = new CSingleton(); return s_singleinstance; gpobj
103 CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) s_singleinstance = new CSingleton(); return s_singleinstance; gpobj
104 CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) s_singleinstance = new CSingleton(); return s_singleinstance; gpobj
105 CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) s_singleinstance = new CSingleton(); return s_singleinstance; gpobj
106 CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) s_singleinstance = new CSingleton(); return s_singleinstance; gpobj someobj
107 CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) s_singleinstance = new CSingleton(); return s_singleinstance; gpobj someobj
108 CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) s_singleinstance = new CSingleton(); return s_singleinstance; gpobj someobj
109 CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) s_singleinstance = new CSingleton(); return s_singleinstance; gpobj someobj
110 CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) s_singleinstance = new CSingleton(); return s_singleinstance; gpobj someobj
111 CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) s_singleinstance = new CSingleton(); return s_singleinstance; gpobj sndobj
112 CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) s_singleinstance = new CSingleton(); return s_singleinstance; gpobj sndobj
113 Two Singletons Depending on where context switches occur we can get two singleton objects created The first is a phantom The thread using it will get the second object created next time it calls GetSingleton()
114 Concurrent Singleton Put a lock around the whole code MutEx Use Java s synchronized keyword Concurrency issue only when creating the object So no need to lock when returning the object
115 Better Locking Only get a problem the first time GetSingleton() is called Move to eager object creation (at load time?) Or use finer-grain locking? Finer-grain locks best, but with their own issues
116 Here we lock a mutex while we create the singleton, however we still have the same problem if the context switch happens after the conditional (and before the LOCK happens) How can we get around this? CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) LOCK(someMutex); s_singleinstance = new CSingleton(); UNLOCK(someMutex); return s_singleinstance;
117 CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) LOCK(someMutex); if(null == s_singleinstance) s_singleinstance = new CSingleton (); UNLOCK(someMutex); return s_singleinstance; Once we have the lock then we check the variable again, to see if it got changed
118 Double-checked Lock This is called double-checked locking We check the variable to see if we need to get the lock Then we acquire the lock Then we check it again to see if it changed while we tried to get the lock
119 CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) LOCK(someMutex); if(null == s_singleinstance) s_singleinstance = new CSingleton (); UNLOCK(someMutex); return s_singleinstance;
120 Almost there But there is another problems Compilers are too clever by half It assumes that the private static variable cannot be changed between the two conditionals Have to tell the compiler it might change using volatile keyword
121 volatile CSingleton * CSingleton::s_singleInstance = NULL; CSingleton *CSingleton::GetSingleton() if(null == s_singleinstance) LOCK(someMutex); if(null == s_singleinstance) s_singleinstance = new CSingleton(); UNLOCK(someMutex); return s_singleinstance; Finally, a multi-thread safe Singleton implementation
122 Thread-safe Singleton Can t be done in Java less than Java 5, consider other methods Can t be done in C++ at all Because the CPU can reorder the instructions on-the-fly Need to use assembler or external libraries to get around this
123 Bet you didn t think creating an object could be so complicated
g Baking with OO Goodness
4 the Factory Pattern h g Baking with OO Goodness g Get ready to bake some loosely coupled OO designs. There is more to making objects than just using the new operator. You ll learn that instantiation
More informationIf we aren t supposed to program to an implementation then how can we actually create new things? Reptile reptile = new Turtle(); Software Engineering
CSC40232: SOFTWARE ENGINEERING Professor: Jane Cleland Huang Lecture 3: Observer Pattern Wednesday, January 18 th sarec.nd.edu/courses/se2017 Department of Computer Science and Engineering If we aren t
More informationApplying the Factory Method Design Pattern
Applying the Factory Method Design Pattern Trenton Computer Festival Professional Seminars Michael P. Redlich (908) 730-3416 michael.p.redlich@exxonmobil.com About Myself Degree B.S. in Computer Science
More informationLaboratorio di Tecnologie dell'informazione. Ing. Marco Bertini
Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini bertini@dsi.unifi.it http://www.dsi.unifi.it/~bertini/ Design pattern Factory Some motivations Consider a user interface toolkit to support
More informationTDDB84 Design Patterns Lecture 02. Factory Method, Decorator
Lecture 02 Factory Method, Decorator Peter Bunus Dept of Computer and Information Science Linköping University, Sweden petbu@ida.liu.se Factory Method Pattern Peter Bunus 2 1 Time for Lunch Joe, with the
More informationSoftware Design COSC 4353/6353 D R. R A J S I N G H
Software Design COSC 4353/6353 D R. R A J S I N G H Creational Design Patterns What are creational design patterns? Types Examples Structure Effects Creational Patterns Design patterns that deal with object
More informationThe Strategy Pattern Design Principle: Design Principle: Design Principle:
Strategy Pattern The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Design
More informationA few important patterns and their connections
A few important patterns and their connections Perdita Stevens School of Informatics University of Edinburgh Plan Singleton Factory method Facade and how they are connected. You should understand how to
More informationPlan. A few important patterns and their connections. Singleton. Singleton: class diagram. Singleton Factory method Facade
Plan A few important patterns and their connections Perdita Stevens School of Informatics University of Edinburgh Singleton Factory method Facade and how they are connected. You should understand how to
More informationDesign Pattern- Creational pattern 2015
Creational Patterns Abstracts instantiation process Makes system independent of how its objects are created composed represented Encapsulates knowledge about which concrete classes the system uses Hides
More informationRules and syntax for inheritance. The boring stuff
Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for
More informationCS342: Software Design. November 21, 2017
CS342: Software Design November 21, 2017 Runnable interface: create threading object Thread is a flow of control within a program Thread vs. process All execution in Java is associated with a Thread object.
More informationLaboratorio di Progettazione di Sistemi Software Design Pattern Creazionali. Valentina Presutti (A-L) Riccardo Solmi (M-Z)
Laboratorio di Progettazione di Sistemi Software Design Pattern Creazionali Valentina Presutti (A-L) Riccardo Solmi (M-Z) Indice degli argomenti Catalogo di Design Patterns creazionali: Abstract Factory
More informationThe Factory Method Design Pattern
The Factory Method Design Pattern Some common applications A factory method is used to create objects, whose subclasses can then override to specify the derived type of product that will be created More
More informationDesign Patterns. CSCE Lecture 17-10/28/2015 (Partially adapted from Head First Design Patterns by Freeman, Bates, Sierra, and Robson)
Design Patterns CSCE 740 - Lecture 17-10/28/2015 (Partially adapted from Head First Design Patterns by Freeman, Bates, Sierra, and Robson) OO Design Exercise: Building a Better Duck Duck quack() swim()
More informationWhat is Design Patterns?
Paweł Zajączkowski What is Design Patterns? 1. Design patterns may be said as a set of probable solutions for a particular problem which is tested to work best in certain situations. 2. In other words,
More informationSoftware Paradigms (Lesson 3) Object-Oriented Paradigm (2)
Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3
More informationDesign Patterns Cont. CSE 110 Discussion - Week 9
Design Patterns Cont. CSE 110 Discussion - Week 9 Factory Method - Decouple object creation from implementation details - Allows you to use an object ( product ) without knowing about creation - Often
More informationInheritance, and Polymorphism.
Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to
More informationObject-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018
Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 4: OO Principles - Polymorphism http://courses.cs.cornell.edu/cs2110/2018su Lecture 3 Recap 2 Good design principles.
More informationDesign Patterns. Manuel Mastrofini. Systems Engineering and Web Services. University of Rome Tor Vergata June 2011
Design Patterns Lecture 1 Manuel Mastrofini Systems Engineering and Web Services University of Rome Tor Vergata June 2011 Definition A pattern is a reusable solution to a commonly occurring problem within
More informationTest-Driven Development (TDD)
Test-Driven Development (TDD) CS 4501 / 6501 Software Testing [Lasse Koskela, Test Driven, Chapters 2-3] 1 Agile Airplane Testing Test harness: Appearance matches Color coding in place Fly 6ft (or 2m)
More informationDesign Patterns: State, Bridge, Visitor
Design Patterns: State, Bridge, Visitor State We ve been talking about bad uses of case statements in programs. What is one example? Another way in which case statements are sometimes used is to implement
More informationAgile Architecture. The Why, the What and the How
Agile Architecture The Why, the What and the How Copyright Net Objectives, Inc. All Rights Reserved 2 Product Portfolio Management Product Management Lean for Executives SAFe for Executives Scaled Agile
More informationCreational Patterns. Factory Method (FM) Abstract Factory (AF) Singleton (SI) Prototype (PR) Builder (BU)
Creational Patterns Creational Patterns Factory Method (FM) Abstract Factory (AF) Singleton (SI) Prototype (PR) Builder (BU) Factory Method (FM) Intent: Define an interface for creating an object, but
More informationCSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich
CSCD01 Engineering Large Software Systems Design Patterns Joe Bettridge Winter 2018 With thanks to Anya Tafliovich Design Patterns Design patterns take the problems consistently found in software, and
More informationIntroduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1
Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Inheritance Consider a new type Square. Following how we declarations for the Rectangle and Circle classes we could declare it as follows:
More informationJava Threads and intrinsic locks
Java Threads and intrinsic locks 1. Java and OOP background fundamentals 1.1. Objects, methods and data One significant advantage of OOP (object oriented programming) is data encapsulation. Each object
More informationWhat is Design Patterns?
Paweł Zajączkowski What is Design Patterns? 1. Design patterns may be said as a set of probable solutions for a particular problem which is tested to work best in certain situations. 2. In other words,
More informationThe Factory Pattern. Ballplayer joe = new Ballplayer("Dimaggio","OF");
Chapter 10 The Factory Pattern Now that we ve covered inheritance, we re in a position to understand the next simple-yet-ubiquitous design pattern, called Factory. It s a pretty easy one to grasp. Simply
More informationJava Object Oriented Design. CSC207 Fall 2014
Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code
More informationTDDB84. Lecture 2. fredag 6 september 13
TDDB84 Lecture 2 Yes, you can bring the books to the exam Creational Factory method Structural Decorator Behavioral LE2 Creational Abstract Factory Singleton Builder Structural Composite Proxy Bridge Adapter
More informationCOMP 6471 Software Design Methodologies
COMP 6471 Software Design Methodologies Fall 2011 Dr Greg Butler http://www.cs.concordia.ca/~gregb/home/comp6471-fall2011.html Week 8 Outline Software Design Patterns Overview of Patterns Present solutions
More informationCS 351 Design of Large Programs Singleton Pattern
CS 351 Design of Large Programs Singleton Pattern Brooke Chenoweth University of New Mexico Spring 2019 The Notion of a Singleton There are many objects we only need one of: Thread pools, caches, dialog
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance (part II) Polymorphism Version of January 21, 2013 Abstract These lecture notes
More informationC++ Inheritance and Encapsulation
C++ Inheritance and Encapsulation Private and Protected members Inheritance Type Public Inheritance Private Inheritance Protected Inheritance Special method inheritance 1 Private Members Private members
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance (part II) Polymorphism Version of January 21, 2013 Abstract These lecture notes
More informationWhat is a Pattern? Lecture 40: Design Patterns. Elements of Design Patterns. What are design patterns?
What is a Pattern? Lecture 40: Design Patterns CS 62 Fall 2017 Kim Bruce & Alexandra Papoutsaki "Each pattern describes a problem which occurs over and over again in our environment, and then describes
More informationCreational Design Patterns
Creational Design Patterns Creational Design Patterns Structural Design Patterns Behavioral Design Patterns GoF Design Pattern Categories Purpose Creational Structural Behavioral Scope Class Factory Method
More informationDesign Pattern and Software Architecture: IV. Design Pattern
Design Pattern and Software Architecture: IV. Design Pattern AG Softwaretechnik Raum E 3.165 Tele.. 60-3321 hg@upb.de IV. Design Pattern IV.1 Introduction IV.2 Example: WYSIWYG Editor Lexi IV.3 Creational
More informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More informationCS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers
CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers 1 Critical sections and atomicity We have been seeing that sharing mutable objects between different threads is tricky We need some
More informationEINDHOVEN UNIVERSITY OF TECHNOLOGY
EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics & Computer Science Exam Programming Methods, 2IP15, Wednesday 17 April 2013, 09:00 12:00 TU/e THIS IS THE EXAMINER S COPY WITH (POSSIBLY INCOMPLETE)
More informationWhat is Design Patterns?
Paweł Zajączkowski What is Design Patterns? 1. Design patterns may be said as a set of probable solutions for a particular problem which is tested to work best in certain situations. 2. In other words,
More informationLearning from Bad Examples. CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014
Learning from Bad Examples CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014 1 Goals Demonstrate techniques to design for shared mutability Build on an example where multiple threads
More informationECE 449 OOP and Computer Simulation Lecture 11 Design Patterns
ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 1/60 ECE 449 OOP and Computer Simulation Lecture 11 Design Patterns Professor Jia Wang Department of Electrical
More informationMSO Object Creation Singleton & Object Pool
MSO Object Creation Singleton & Object Pool Wouter Swierstra & Hans Philippi October 25, 2018 Object Creation: Singleton & Object Pool 1 / 37 This lecture How to create objects The Singleton Pattern The
More informationObject-Oriented Concepts and Design Principles
Object-Oriented Concepts and Design Principles Signature Specifying an object operation or method involves declaring its name, the objects it takes as parameters and its return value. Known as an operation
More information1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides
1B1b Inheritance Agenda Introduction to inheritance. How Java supports inheritance. Inheritance is a key feature of object-oriented oriented programming. 1 2 Inheritance Models the kind-of or specialisation-of
More informationCSE 70 Final Exam Fall 2009
Signature cs70f Name Student ID CSE 70 Final Exam Fall 2009 Page 1 (10 points) Page 2 (16 points) Page 3 (22 points) Page 4 (13 points) Page 5 (15 points) Page 6 (20 points) Page 7 (9 points) Page 8 (15
More informationCS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes
CS/ENGRD 2110 FALL 2017 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due tomorrow night (17 February) Get started on A3 a method every other day.
More informationindex.pdf January 21,
index.pdf January 21, 2013 1 ITI 1121. Introduction to Computing II Circle Let s complete the implementation of the class Circle. Marcel Turcotte School of Electrical Engineering and Computer Science Version
More informationThe Singleton Pattern. Design Patterns In Java Bob Tarr
The Singleton Pattern Intent Ensure a class only has one instance, and provide a global point of access to it Motivation Sometimes we want just a single instance of a class to exist in the system For example,
More informationCS 370 Design Heuristics D R. M I C H A E L J. R E A L E F A L L
CS 370 Design Heuristics D R. M I C H A E L J. R E A L E F A L L 2 0 1 5 Introduction Now we ll talk about ways of thinking about design Guidelines for trials in trial and errors Major Design Heuristics
More informationWriting your own Java I/O Decorator p. 102 Tools for your Design Toolbox p. 105 Exercise Solutions p. 106 The Factory Pattern Baking with OO
Intro to Design Patterns Welcome to Design Patterns: Someone has already solved your problems The SimUDuck app p. 2 Joe thinks about inheritance... p. 5 How about an interface? p. 6 The one constant in
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationDesign Patterns Reid Holmes
Material and some slide content from: - Head First Design Patterns Book - GoF Design Patterns Book Design Patterns Reid Holmes GoF design patterns $ %!!!! $ "! # & Pattern vocabulary Shared vocabulary
More informationThe GoF Design Patterns Reference
The GoF Design Patterns Reference Version.0 / 0.0.07 / Printed.0.07 Copyright 0-07 wsdesign. All rights reserved. The GoF Design Patterns Reference ii Table of Contents Preface... viii I. Introduction....
More informationCSCI 253. Overview. The Elements of a Design Pattern. George Blankenship 1. Object Oriented Design: Creational Patterns. George Blankenship
CSCI 253 Object Oriented Design: George Blankenship George Blankenship 1 Singleton Abstract factory Factory Method Prototype Builder Overview Structural Patterns Composite Façade Proxy Flyweight Adapter
More informationSDC Design patterns GoF
SDC Design patterns GoF Design Patterns The design pattern concept can be viewed as an abstraction of imitating useful parts of other software products. The design pattern is a description of communicating
More informationModellistica Medica. Maria Grazia Pia, INFN Genova. Scuola di Specializzazione in Fisica Sanitaria Genova Anno Accademico
Modellistica Medica Maria Grazia Pia INFN Genova Scuola di Specializzazione in Fisica Sanitaria Genova Anno Accademico 2002-2003 Lezione 8 OO modeling Design Patterns Introduction Creational Patterns Software
More informationPatterns Continued and Concluded. July 26, 2017
Patterns Continued and Concluded July 26, 2017 Review Quiz What is the purpose of the Singleton pattern? A. To advertise to other developers that the object should only be modified by `main()` B.To prevent
More informationOODP Session 5a. Web Page: Visiting Hours: Tuesday 17:00 to 19:00
OODP Session 5a Next week: Reading week Session times PT group 1 Monday 18:00 21:00 room: Malet 403 PT group 2 Thursday 18:00 21:00 room: Malet 407 FT Tuesday 13:30 17:00 room: Malet 404 Email: oded@dcs.bbk.ac.uk
More informationThe object-oriented approach goes a step further by providing tools for the programmer to represent elements in the problem space.
1 All programming languages provide abstractions. Assembly language is a small abstraction of the underlying machine. Many imperative languages (FORTRAN, BASIC, and C) are abstractions of assembly language.
More informationDay 5. COMP1006/1406 Summer M. Jason Hinek Carleton University
Day 5 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments Assignment 2 is in Assignment 3 is out a quick look back inheritance and polymorphism interfaces the Comparable
More informationCS 251 Intermediate Programming Inheritance
CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?
More informationJAVA: A Primer. By: Amrita Rajagopal
JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently
More informationMSO Lecture 12. Wouter Swierstra (adapted by HP) October 26, 2017
1 MSO Lecture 12 Wouter Swierstra (adapted by HP) October 26, 2017 2 LAST LECTURE Analysis matrix; Decorator pattern; Model-View-Controller; Observer pattern. 3 THIS LECTURE How to create objects 4 CATEGORIES
More informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module
More informationLecture 5: Inheritance
McGill University Computer Science Department COMP 322 : Introduction to C++ Winter 2009 Lecture 5: Inheritance Sami Zhioua March 11 th, 2009 1 Inheritance Inheritance is a form of software reusability
More informationSuper-Classes and sub-classes
Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an
More informationDesign Patterns. SE3A04 Tutorial. Jason Jaskolka
SE3A04 Tutorial Jason Jaskolka Department of Computing and Software Faculty of Engineering McMaster University Hamilton, Ontario, Canada jaskolj@mcmaster.ca November 18/19, 2014 Jason Jaskolka 1 / 35 1
More informationINHERITANCE. Spring 2019
INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose
More informationInheritance and Polymorphism in Java
Inheritance and Polymorphism in Java Introduction In this article from my free Java 8 course, I will be discussing inheritance in Java. Similar to interfaces, inheritance allows a programmer to handle
More informationSynchronization SPL/2010 SPL/20 1
Synchronization 1 Overview synchronization mechanisms in modern RTEs concurrency issues places where synchronization is needed structural ways (design patterns) for exclusive access 2 Overview synchronization
More informationWeek 7. Statically-typed OO languages: C++ Closer look at subtyping
C++ & Subtyping Week 7 Statically-typed OO languages: C++ Closer look at subtyping Why talk about C++? C++ is an OO extension of C Efficiency and flexibility from C OO program organization from Simula
More informationPolymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism
CMSC 330: Organization of Programming Languages Polymorphism Polymorphism Definition Feature that allows values of different data types to be handled using a uniform interface Applicable to Functions Ø
More informationChapter 14 Abstract Classes and Interfaces
Chapter 14 Abstract Classes and Interfaces 1 What is abstract class? Abstract class is just like other class, but it marks with abstract keyword. In abstract class, methods that we want to be overridden
More informationDesign Patterns. Design Patterns 1. Outline. Design Patterns. Bicycles Simulator 10/26/2011. Commonly recurring patterns of OO design
G52APR Applications Programming Design Patterns 1 Design Patterns What is design patterns? The design patterns are languageindependent strategies for solving common object-oriented design problems. Jiawei
More informationCS 251 Intermediate Programming Methods and Classes
CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
More informationCS 251 Intermediate Programming Methods and More
CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
More informationMore About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario
More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario The Story So Far... Classes as collections of fields and methods. Methods can access fields, and
More informationCS 241 Honors Concurrent Data Structures
CS 241 Honors Concurrent Data Structures Bhuvan Venkatesh University of Illinois Urbana Champaign March 27, 2018 CS 241 Course Staff (UIUC) Lock Free Data Structures March 27, 2018 1 / 43 What to go over
More informationQUIZ. What is wrong with this code that uses default arguments?
QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code
More informationAbstract. 1. What is an ABSTRACT METHOD? 2. Why you would want to declare a method as abstract? 3. A non-abstract CLASS is called a concrete class
ABSTRACT 2 1. What is an ABSTRACT METHOD? 2 2. Why you would want to declare a method as abstract? 2 3. A non-abstract CLASS is called a concrete class 2 4. Abstract Example 2 5. If you are extending ABSTRACT
More informationIntro. Scheme Basics. scm> 5 5. scm>
Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if
More informationCSE 374 Programming Concepts & Tools
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2017 Lecture 22 Shared-Memory Concurrency 1 Administrivia HW7 due Thursday night, 11 pm (+ late days if you still have any & want to use them) Course
More informationadministrivia today UML start design patterns Tuesday, September 28, 2010
administrivia Assignment 2? promise to get past assignment 1 back soon exam on monday review slides are posted your responsibility to review covers through last week today UML start design patterns 1 Unified
More informationHeap Arrays and Linked Lists. Steven R. Bagley
Heap Arrays and Linked Lists Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index Variables and arrays have a type Create our
More informationIntroduction to Design Patterns
Introduction to Design Patterns First, what s a design pattern? a general reusable solution to a commonly occurring problem within a given context in software design It s not a finished design that can
More informationReference Counting. Steven R. Bagley
Reference Counting Steven R. Bagley Previously Objects are blocks of memory Store pointer to base of object s memory so we can reference it Memory needs to be released when the object is no longer needed
More informationAbstract Classes and Interfaces
Abstract methods Abstract Classes and Interfaces You can declare an object without defining it: Person p; Similarly, you can declare a method without defining it: public abstract void draw(int size); Notice
More informationBuilding custom components IAT351
Building custom components IAT351 Week 1 Lecture 1 9.05.2012 Lyn Bartram lyn@sfu.ca Today Review assignment issues New submission method Object oriented design How to extend Java and how to scope Final
More informationObject Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia
Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing
More informationGoals of Lecture. Lecture 27: OO Design Patterns. Pattern Resources. Design Patterns. Cover OO Design Patterns. Pattern Languages of Programming
Goals of Lecture Lecture 27: OO Design Patterns Cover OO Design Patterns Background Examples Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 6448 - Spring Semester, 2001 April 24, 2001 Kenneth
More informationSchool of Informatics, University of Edinburgh
CS1Bh Solution Sheet 4 Software Engineering in Java This is a solution set for CS1Bh Question Sheet 4. You should only consult these solutions after attempting the exercises. Notice that the solutions
More informationCS/ENGRD 2110 SPRING 2018
CS/ENGRD 2110 SPRING 2018 Lecture 7: Interfaces and http://courses.cs.cornell.edu/cs2110 1 2 St Valentine s Day! It's Valentines Day, and so fine! Good wishes to you I consign.* But since you're my students,
More informationAn Introduction to Patterns
An Introduction to Patterns Robert B. France Colorado State University Robert B. France 1 What is a Pattern? - 1 Work on software development patterns stemmed from work on patterns from building architecture
More informationThreads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015
Threads and Locks CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015 1 Goals Cover the material presented in Chapter 2, Day 1 of our concurrency textbook Creating threads Locks Memory
More informationSoftware Engineering /48
Software Engineering 1 /48 Topics 1. The Compilation Process and You 2. Polymorphism and Composition 3. Small Functions 4. Comments 2 /48 The Compilation Process and You 3 / 48 1. Intro - How do you turn
More information