Design Patterns Lecture 3 Types of Design Patterns



























![Façade Pattern: Code [1] class Scanner // Takes a stream of characters and produces Façade Pattern: Code [1] class Scanner // Takes a stream of characters and produces](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-28.jpg)
![Façade Pattern: Code [2] class parser // Builds a parse tree from tokens using Façade Pattern: Code [2] class parser // Builds a parse tree from tokens using](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-29.jpg)
![Façade Pattern: Code [3] class Pnodebuilder { public: // Builds a parse tree incrementally. Façade Pattern: Code [3] class Pnodebuilder { public: // Builds a parse tree incrementally.](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-30.jpg)
![Façade Pattern: Code [4] class Pnode { // An interface to manipulate the program Façade Pattern: Code [4] class Pnode { // An interface to manipulate the program](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-31.jpg)
![Façade Pattern: Code [5] class Code. Generator { // Generate bytecode. public: // Manipulate Façade Pattern: Code [5] class Code. Generator { // Generate bytecode. public: // Manipulate](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-32.jpg)
![Façade Pattern: Code [6] void Expression. Node: : Traverse (Code. Generator& cg) { cg. Façade Pattern: Code [6] void Expression. Node: : Traverse (Code. Generator& cg) { cg.](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-33.jpg)
![Façade Pattern: Code [7] class Compiler { // Façade. Offers a simple interface to Façade Pattern: Code [7] class Compiler { // Façade. Offers a simple interface to](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-34.jpg)
![Facade Pattern: Another Example from POS [1] • Assume that rules are desired to Facade Pattern: Another Example from POS [1] • Assume that rules are desired to](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-35.jpg)
![Facade Pattern: Another Example [2] • Define a “rule engine” subsystem (e. g. POSRule. Facade Pattern: Another Example [2] • Define a “rule engine” subsystem (e. g. POSRule.](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-36.jpg)
- Slides: 36

Design Patterns Lecture 3

Types of Design Patterns Creational Abstract Factory Builder Factory Prototype Singleton Structural Adapter Bridge Composite Decorator Façade Flyweight Proxy Behavioural Chain of Responsibility Command Interpreter Iterator Mediator Memento Observer State Strategy Template Method Visitor 2



DOM应用图例 public interface Node { public String get. Node. Name(); public short get. Node. Type(); public String get. Prefix(); . . . } public Node get. Parent. Node(); public boolean has. Child. Nodes(); public Node. List get. Child. Nodes(); public Node append. Child(Node new. Child); public Node remove. Child(Node old. Child); public Node insert. Before(Node new. Child, Node ref. Child); . . .






Problem of redundant objects problem: redundant objects can bog down system ◦ many objects have same state ◦ intrinsic vs. extrinsic state ◦ ◦ example: File objects that represent the same file on disk new new. . . new File("mobydick. txt") File("notes. txt") 11

Flyweight pattern flyweight: an assurance that no more than one instance of a class will have identical state ◦ achieved by caching identical instances of objects to reduce object construction ◦ similar to singleton, but has many instances, one for each unique-state object ◦ useful for cases when there are many instances of a type but many are the same ◦ can be used in conjunction with Factory pattern to create a very efficient object-builder ◦ examples in Java: String, Image / Toolkit, Formatter 12

Flyweight and Strings Flyweighted strings ◦ Java Strings are flyweighted by the compiler in many cases ◦ can be flyweighted at runtime with the intern method String fly = "fly", String fly 2 = "fly", weight = "weight"; weight 2 = "weight"; ◦ Which of the following expressions are true? fly == fly 2 weight == weight 2 "fly" + "weight" == "flyweight" fly + weight == "flyweight" String flyweight = new String("fly" + "weight"); flyweight == "flyweight" String interned = (fly + weight). intern(); interned == "flyweight" 13

Implementing a Flyweight flyweighting works best on immutable objects ◦ immutable: cannot be changed once constructed class pseudo-code sketch: public class Flyweighted { ◦ static collection of instances ◦ private constructor ◦ static method to get an instance: } if (we have created this kind of instance before), get it from the collection and return it else, create a new instance, store it in the collection and return it 14

Flyweight sequence diagram 15

Implementing a Flyweight public class Flyweighted { private static Map instances; private Flyweighted() {} public static synchronized Flyweighted get. Instance(Object key) { if (!my. Instances. contains(key)) { Flyweighted fw = new Flyweighted(key); instances. put(key, fw); return fw; } else { return instances. get(key); } } 16

Class before flyweighting A class to be flyweighted public class Point { private int x, y; public Point(int x, int y) { this. x = x; this. y = y; } public int get. X() { return x; } public int get. Y() { return y; } public String to. String() { return "(" + x + ", " + y + ")"; } } 17

Class after flyweighting A class that has been flyweighted! public class Point { private static Map<String, Point> instances = new Hash. Map<String, Point>(); public static Point get. Instance(int x, int y) { String key = x + ", " + y; if (instances. contains. Key(key)) { // re-use existing pt return instances. get(key); } } Point p = new Point(x, y); instances. put(key, p); return p; private final int x, y; // immutable private Point(int x, int y) {. . . 18




Facade Pattern: Problem Client Classes Need to communicate with Subsystem classes 22

Facade Pattern: Solution Client Classes Facade Subsystem classes 23

Facade Pattern: Why and What? • Subsystems often get complex as they evolve. Need to provide a simple interface to many, often small, classes. But not necessarily to ALL classes of the subsystem. • Façade provides a simple default view good enough for most clients. • Facade decouples a subsystem from its clients. • A façade can be a single entry point to each subsystem level. This allows layering. 24

Facade Pattern: Participants and Communication • Participants: Façade and subsystem classes Clients communicate with subsystem classes by sending requests to façade. • Façade forwards requests to the appropriate subsystem classes. • Clients do not have direct access to subsystem classes. 25

Facade Pattern: Benefits • Shields clients from subsystem classes; reduces the number of objects that clients deal with. Promotes weak coupling between subsystem and its clients. • Helps in layering the system. Helps eliminate circular dependencies. 26

Example: A compiler Compiler Invocations Compile() Stream Bytecode. Stream Code. Generator Scanner Token Parser Symbol Pnode. Builder Pnode Statement. Node RISCCodegenerator Expression. Node Stack. Machine. Codegenerator 27
![Façade Pattern Code 1 class Scanner Takes a stream of characters and produces Façade Pattern: Code [1] class Scanner // Takes a stream of characters and produces](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-28.jpg)
Façade Pattern: Code [1] class Scanner // Takes a stream of characters and produces a stream of tokens. { public: Scanner (istream&); virtual Scanner(); virtual Token& Scan(); Private: istream& _input. Stream; }; 28
![Façade Pattern Code 2 class parser Builds a parse tree from tokens using Façade Pattern: Code [2] class parser // Builds a parse tree from tokens using](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-29.jpg)
Façade Pattern: Code [2] class parser // Builds a parse tree from tokens using the PNode. Builder. { public: Parser (); virtual ~Parser() virtual void Parse (Scanner&, PNode. Builder&); }; 29
![Façade Pattern Code 3 class Pnodebuilder public Builds a parse tree incrementally Façade Pattern: Code [3] class Pnodebuilder { public: // Builds a parse tree incrementally.](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-30.jpg)
Façade Pattern: Code [3] class Pnodebuilder { public: // Builds a parse tree incrementally. Parse tree // consists of Pnode objects. Pnodebuilder (); virtual Pnode* New. Variable ( // Node for a variable. Char* variable. Name ) const; virtual Pnode* New. Assignment ( // Node for an assignment. Pnode* variable, Pnode* expression ) const; // Similarly. . . more nodes. Private: Pnode* _node; }; 30
![Façade Pattern Code 4 class Pnode An interface to manipulate the program Façade Pattern: Code [4] class Pnode { // An interface to manipulate the program](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-31.jpg)
Façade Pattern: Code [4] class Pnode { // An interface to manipulate the program node and its children. public: // Manipulate program node. virtual void Get. Source. Position (int& line, int& index); // Manipulate child node. virtual void Add (Pnode*); virtual void Remove (Pnode*); // …. virtual void traverse (Codegenerator&); // Traverse tree to generate code. protected: PNode(); }; 31
![Façade Pattern Code 5 class Code Generator Generate bytecode public Manipulate Façade Pattern: Code [5] class Code. Generator { // Generate bytecode. public: // Manipulate](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-32.jpg)
Façade Pattern: Code [5] class Code. Generator { // Generate bytecode. public: // Manipulate program node. virtual void Visit (Statement. Node*); virtual void Visit (Expression. Node*); // …. Protected: Code. Generator (Bytecode. Stream&); Bytecode. Stream& _output; }; 32
![Façade Pattern Code 6 void Expression Node Traverse Code Generator cg cg Façade Pattern: Code [6] void Expression. Node: : Traverse (Code. Generator& cg) { cg.](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-33.jpg)
Façade Pattern: Code [6] void Expression. Node: : Traverse (Code. Generator& cg) { cg. Visit (this); List. Iterator<Pnode*> i(_children); For (i. First(); !i. Is. Done(); i. Next(); { i. Current. Item() Traverse(cg); }; }; 33
![Façade Pattern Code 7 class Compiler Façade Offers a simple interface to Façade Pattern: Code [7] class Compiler { // Façade. Offers a simple interface to](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-34.jpg)
Façade Pattern: Code [7] class Compiler { // Façade. Offers a simple interface to compile and // Generate code. public: Could also take a Code. Generator Compiler(); Parameter for increased generality. virtual void Compile (istream&, Bytecode. Stream&); } void Compiler: : Compile (istream& input, Bytecode. Stream& output) { Scanner scanner (input); Pnode. Builder builder; Parser parser; parser. Parse (scanner, builder); RISCCode. Generator generator (output); Pnode* parse. Tree = builder. Get. Root. Node(); parse. Tree Traverse (generator); } 34
![Facade Pattern Another Example from POS 1 Assume that rules are desired to Facade Pattern: Another Example from POS [1] • Assume that rules are desired to](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-35.jpg)
Facade Pattern: Another Example from POS [1] • Assume that rules are desired to invalidate an action: – Suppose that when a new Sale is created, it will be paid by a gift certificate ◦ Only one item can be purchased using a gift certificate. – Hence, subsequent enter. Item operations must be invalidated in some cases. (Which ones? ) How does a designer factor out the handling of such rules? 35
![Facade Pattern Another Example 2 Define a rule engine subsystem e g POSRule Facade Pattern: Another Example [2] • Define a “rule engine” subsystem (e. g. POSRule.](https://slidetodoc.com/presentation_image_h2/69f33f2f6e3900874453e5ba07232c2e/image-36.jpg)
Facade Pattern: Another Example [2] • Define a “rule engine” subsystem (e. g. POSRule. Engine. Facade). • It evaluates a set of rules against an operation and indicates if the rule has invalidated an operation. Calls to this façade are placed near the start of the methods that need to be validated. – Example: Invoke the façade to check if a new sales. Line. Item created by make. Line. Item is valid or not. 36