44
CS Software Development Design Patterns October , CS October , /

CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

CS 4500Software Development

Design Patterns

October 11, 2019

CS 4500 October 11, 2019 1 / 33

Page 2: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Motivation

Many design issues / challenges:• Have been faced before• Have been addressed and solved repeatedly• Some solutions are more successful than others• Abstraction of solutions to design problems = design pattern

CS 4500 October 11, 2019 2 / 33

Page 3: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Design Patterns

• Goal: not to solve every problem from �rst principles

• Simple and elegant solutions to speci�c (recurring) problems incomponent design

• A three-part rule – expresses a relation between a certain context, aproblem, and a solution

• Captures design knowledge in a way that allows others to use thatknowledge

• Originated in OOD, but applicable to other approaches to modulardesign

• Seen some in CS3500

CS 4500 October 11, 2019 3 / 33

Page 4: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Design Patterns

• Goal: not to solve every problem from �rst principles• Simple and elegant solutions to speci�c (recurring) problems incomponent design

• A three-part rule – expresses a relation between a certain context, aproblem, and a solution

• Captures design knowledge in a way that allows others to use thatknowledge

• Originated in OOD, but applicable to other approaches to modulardesign

• Seen some in CS3500

CS 4500 October 11, 2019 3 / 33

Page 5: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Design Patterns

• Goal: not to solve every problem from �rst principles• Simple and elegant solutions to speci�c (recurring) problems incomponent design

• A three-part rule – expresses a relation between a certain context, aproblem, and a solution

• Captures design knowledge in a way that allows others to use thatknowledge

• Originated in OOD, but applicable to other approaches to modulardesign

• Seen some in CS3500

CS 4500 October 11, 2019 3 / 33

Page 6: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Design Patterns

• Goal: not to solve every problem from �rst principles• Simple and elegant solutions to speci�c (recurring) problems incomponent design

• A three-part rule – expresses a relation between a certain context, aproblem, and a solution

• Captures design knowledge in a way that allows others to use thatknowledge

• Originated in OOD, but applicable to other approaches to modulardesign

• Seen some in CS3500

CS 4500 October 11, 2019 3 / 33

Page 7: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Design Patterns

• Goal: not to solve every problem from �rst principles• Simple and elegant solutions to speci�c (recurring) problems incomponent design

• A three-part rule – expresses a relation between a certain context, aproblem, and a solution

• Captures design knowledge in a way that allows others to use thatknowledge

• Originated in OOD, but applicable to other approaches to modulardesign

• Seen some in CS3500

CS 4500 October 11, 2019 3 / 33

Page 8: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Design Patterns

• Goal: not to solve every problem from �rst principles• Simple and elegant solutions to speci�c (recurring) problems incomponent design

• A three-part rule – expresses a relation between a certain context, aproblem, and a solution

• Captures design knowledge in a way that allows others to use thatknowledge

• Originated in OOD, but applicable to other approaches to modulardesign

• Seen some in CS3500

CS 4500 October 11, 2019 3 / 33

Page 9: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

E�ective Design Patterns

Solve a problem Capture solutions, not just abstract principles orstrategies.

Proven concept Capture solutions with a track record, not theories orspeculation.

Solution isn’t obvious Best patterns generate a solution to a problemindirectly

Describes a relationship Patterns don’t just describe modules, describedeeper system structures and mechanisms.

Signi�cant human component Best patterns explicitly appeal toaesthetics and utility.

CS 4500 October 11, 2019 4 / 33

Page 10: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

E�ective Design Patterns

Solve a problem Capture solutions, not just abstract principles orstrategies.

Proven concept Capture solutions with a track record, not theories orspeculation.

Solution isn’t obvious Best patterns generate a solution to a problemindirectly

Describes a relationship Patterns don’t just describe modules, describedeeper system structures and mechanisms.

Signi�cant human component Best patterns explicitly appeal toaesthetics and utility.

CS 4500 October 11, 2019 4 / 33

Page 11: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

E�ective Design Patterns

Solve a problem Capture solutions, not just abstract principles orstrategies.

Proven concept Capture solutions with a track record, not theories orspeculation.

Solution isn’t obvious Best patterns generate a solution to a problemindirectly

Describes a relationship Patterns don’t just describe modules, describedeeper system structures and mechanisms.

Signi�cant human component Best patterns explicitly appeal toaesthetics and utility.

CS 4500 October 11, 2019 4 / 33

Page 12: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

E�ective Design Patterns

Solve a problem Capture solutions, not just abstract principles orstrategies.

Proven concept Capture solutions with a track record, not theories orspeculation.

Solution isn’t obvious Best patterns generate a solution to a problemindirectly

Describes a relationship Patterns don’t just describe modules, describedeeper system structures and mechanisms.

Signi�cant human component Best patterns explicitly appeal toaesthetics and utility.

CS 4500 October 11, 2019 4 / 33

Page 13: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

E�ective Design Patterns

Solve a problem Capture solutions, not just abstract principles orstrategies.

Proven concept Capture solutions with a track record, not theories orspeculation.

Solution isn’t obvious Best patterns generate a solution to a problemindirectly

Describes a relationship Patterns don’t just describe modules, describedeeper system structures and mechanisms.

Signi�cant human component Best patterns explicitly appeal toaesthetics and utility.

CS 4500 October 11, 2019 4 / 33

Page 14: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

A Pattern Language• DPs originated in architecture

Ï but inspired by CS

“Each pattern describes a problem which occursover and over again in our environment, and thendescribes the core of the solution to that problem,in such a way that you can use this solution a mil-lion times over, without ever doing it the same waytwice”

“Each solution is stated in such a way that it givesthe essential �eld of relationships needed to solvethe problem, but in a very general and abstractway—so you can solve the problem for yourself, inyour own way, by adapting it to your preferences,and the local conditions at the place where you aremaking it.”

A Pattern Language (1977)– contains 253 patterns ofarchitectural and urbandesign

CS 4500 October 11, 2019 5 / 33

Page 15: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Design Patterns as a Language

• Organization principle for software components• Guides design of components• DP catalogs – usually presented using a template:

Ï DP nameÏ Problem it addressesÏ Motivation – exampleÏ ApplicabilityÏ ConsequencesÏ . . .

CS 4500 October 11, 2019 6 / 33

Page 16: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Design Patterns as a Language

• Shared design knowledge• Recognizable

Ï ReadabilityÏ MaintainabilityÏ Easier communication

CS 4500 October 11, 2019 7 / 33

Page 17: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Classi�cation

DesignPatterns

Creational

Structural

Behavioral

• Also: Concurrent

CS 4500 October 11, 2019 8 / 33

Page 18: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

“Gang of Four” Patterns

Creational• Abstract Factory• Builder‡

• Factory Method• Prototype• Singleton

Structural• Adapter‡

• Bridge• Composite• Decorator‡

• Facade• Flyweight• Proxy

Behavioral• Chain of Responsibility• Command‡

• Interpreter• Mediator• Memento• Observer• State• Strategy‡

• Template Method• Visitor

‡Possibly seen in CS3500. . . ?

CS 4500 October 11, 2019 9 / 33

Page 19: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Creational Patterns

• Abstract the instantiation process of objects• Make system independent from how its objects are created• Creation, composition, representation of objects• Encapsulate all knowledge about which concrete classes the systemis using

• Hide how instances of these classes are created and put together

CS 4500 October 11, 2019 10 / 33

Page 20: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

BuilderExample

Constraint: the shape of a Labyrinth is immutable

class Labyrinth {private Node[] nodes;private Edge[] edges;

public Labyrinth(Collection<Node> nodes, Collection<Edge> edges) { ... }...

CS 4500 October 11, 2019 11 / 33

Page 21: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Use:

Node nodeA = new Node("A");Node nodeB = new Node("B");Node nodeC = new Node("C");

ArrayList<Node> nodes = new ArrayList();nodes.add(nodeA);nodes.add(nodeB);nodes.add(nodeC);TreeSet<Edge> edges = new TreeSet(

Arrays.asList(new Edge(nodeA, nodeB), new Edge(nodeB, nodeC)));Labyrinth lab = new Labyrinth(nodes, edges);...

CS 4500 October 11, 2019 12 / 33

Page 22: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

With a Builder Interfaceclass Labyrinth {

private Node[] nodes;private Edge[] edges;

private Labyrinth(Node[] nodes, Edge[] edges) {public static Builder getBuilder() { return new Builder(); }

public static class Builder {private Edge[] edges;private Node[] nodes;

public Builder();public void addNode(String name);public void addEdge(String from, String to);public Labyrinth build() { ... }

}...

CS 4500 October 11, 2019 13 / 33

Page 23: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Use:

Labyrinth.Builder builder = Labyrinth.getBuilder();builder.addNode("A");builder.addNode("B");builder.addEdge("A", "B");builder.addNode("C");builder.addEdge("B", "C");Labyrinth lab = builder.build();

CS 4500 October 11, 2019 14 / 33

Page 24: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

BuilderWith Chaining

Alternatively:

public static class Builder {...public Builder();public Builder addNode(String name);public Builder addEdge(String from, String to);public Labyrinth build();

}...

CS 4500 October 11, 2019 15 / 33

Page 25: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Use:

Labyrinth lab = Labyrinth.getBuilder().addNode("A").addNode("B").addEdge("A", "B").addNode("C").addEdge("B", "C").build();

CS 4500 October 11, 2019 16 / 33

Page 26: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Builder

• Situation: we have an object that, upon creation, can be set up incomplex ways

• Maybe we also have a default con�guration, or a few defaultcon�gurations

• Goal: separate object creation and con�guration from itsrepresentation

CS 4500 October 11, 2019 17 / 33

Page 27: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Singletonclass Logger {

public Logger(String filename);public void warning(String message);public void info(String message);...

}

class Foo {public Foo(Logger logger) {... new Bar(logger) ...

}

Logger logger = new Logger("log");Foo foo1 = new Foo(logger);...Foo foo2 = new Foo(logger);

CS 4500 October 11, 2019 18 / 33

Page 28: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Singleton

class Logger {private Logger instance = null;public static Logger getInstance() {

if (instance == null) {this.instance = new Logger("log");

}return this.instance;

}

public log(String message) { ... }

private Logger(String filename) { ... }}

• Careful about multiple threads

CS 4500 October 11, 2019 19 / 33

Page 29: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Singleton

class Logger {private Logger instance = null;public static Logger getInstance() {

if (instance == null) {this.instance = new Logger("log");

}return this.instance;

}

public log(String message) { ... }

private Logger(String filename) { ... }}

• Careful about multiple threadsCS 4500 October 11, 2019 19 / 33

Page 30: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Singleton

• Used to limit to a single instance of a class• Single global access point to instance• Unlike static, enforces initialization• E.g.: database connection manager, logging service

• Somewhat controversial – global point of entry – might obscurecontrol �ow

CS 4500 October 11, 2019 20 / 33

Page 31: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Singleton

• Used to limit to a single instance of a class• Single global access point to instance• Unlike static, enforces initialization• E.g.: database connection manager, logging service• Somewhat controversial – global point of entry – might obscurecontrol �ow

CS 4500 October 11, 2019 20 / 33

Page 32: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Structural Patterns

• Focus: how classes and objects are composed to form largerstructures

• Help establish relationships between entities within a system• “Class patterns”: compose interfaces or implementations• “Object patterns”: compose objects to realize new functionality

CS 4500 October 11, 2019 21 / 33

Page 33: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Adapter

• Converts between interfaces: Adaptee and Target• If an object provides a di�erent interface than a client expects• Two approaches:

Ï Object adapter: implements Target’s interface by maintaining an instance ofAdaptee delegating to it at runtime

Ï Class-based: implements Target’s interface and inherits from Adaptee atcompile-time

CS 4500 October 11, 2019 22 / 33

Page 34: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Adapterinterface Array<T> {

T get(int index);}

interface Iterable<T> {Iterator<T> iterator();

}

interface Iterator<T> {T next();T prev();T reset();

}

class IterableAsArray<T> implements Array<T>{T get(int index) { ... }

}

CS 4500 October 11, 2019 23 / 33

Page 35: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Proxy

• Provide a surrogate or a place holder for another object• Allows controlling access to the object it represents• Implements the same interface as the real subject

Ï Prevents complicating the client of the real subjectÏ Clients can’t tell if they are using a surrogate

• Scenarios:Ï Delaying the initialization of an expensive resource – on-demand loading –virtual proxy

Ï Caching for a slow connectionÏ Control access based on access rights – protection proxyÏ Local representation for a remote object – remote proxyÏ Ensuring that a resource is locked before it’s accessed – smart proxy

CS 4500 October 11, 2019 24 / 33

Page 36: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

public interface Image {void display();

}

public class RealImage implements Image {public RealImage(String fileName) { loadFromDisk(fileName); }public void display() { ... }private void loadFromDisk(String fileName) { ... }

}

public class ProxyImage implements Image{private RealImage realImage = null;public ProxyImage(String fileName) { ... }public void display() {

if (realImage == null)realImage = new RealImage(fileName);

realImage.display();}

}

CS 4500 October 11, 2019 25 / 33

Page 37: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Remote Proxy

• Represents a remote resource locally• Useful, e.g., when switching between a local to a remoteimplementation

• Hiding that the system is distributed• Example: local �le access→ WebDAV• Example: using a remote service to render an image

CS 4500 October 11, 2019 26 / 33

Page 38: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Remote Proxy

interface Labyrinth {public void create(Set<Node> nodes, Set<Edge> edges);public void addToken(Node node, Color token);public bool reachable(Color token, Node node);

}

class LocalLabyrinth implements Labyrinth { ... }

class TCPLabyrinth implements Labyrinth {public TCPLabyrinth(String host, int port) { ... }...public void addToken(Node node, Color token) { ... sendRequest; ... }

}

CS 4500 October 11, 2019 27 / 33

Page 39: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Behavioral

• Algorithms• Assignment of responsibilities between objects• Patterns of communication between objects• Characterize complex control �ow• Shift focus: from �ow of control toward the way objects areinterconnected

CS 4500 October 11, 2019 28 / 33

Page 40: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Observer

• An object (subject) maintains a list of observers• Observers get noti�ed of state changes• Scenarios:

Ï Update multiple views of the same data when the data changesÏ Clients perform actions in lock-step and need to be noti�ed of the tick of acommon clock

• Careful: avoid a chain of observers

CS 4500 October 11, 2019 29 / 33

Page 41: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

interface Observer<T> {void update(T data);

}

interface Subject<T> {public void attach(Observer<T> observer);public void detach(Observer<T> observer);public void notify();

}

CS 4500 October 11, 2019 30 / 33

Page 42: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Applicability / Discussion

• Are common design patterns applicable in your language?• Are they needed?• How about di�erent paradigms?

CS 4500 October 11, 2019 31 / 33

Page 43: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Resources

• Gamma, Helm, Johnson & Vlissides. Design Patterns: Elements ofReusable Object-Oriented Software. 1995 – aka the Gang of Four

• Freeman, Robson, Bates, Sierra. Head First Design Patterns. 2004• https://en.wikipedia.org/wiki/Software_design_pattern• https://refactoring.guru/design-patterns/catalog

CS 4500 October 11, 2019 32 / 33

Page 44: CS 4500 Software Development - Vesely · † Creation, composition, representation of objects † Encapsulate all knowledge about which concrete classes the system is using † Hide

Summary

Design Patterns• Successful solutions to software design problems – abstracted• A language for building software components• Available as repositories of patterns

CS 4500 October 11, 2019 33 / 33