Presentation is loading. Please wait.

Presentation is loading. Please wait.

How Would You Solve This? l Suppose that you want to have one and only one instance of a class – Can you think of ever only wanting one instance of a class?

Similar presentations


Presentation on theme: "How Would You Solve This? l Suppose that you want to have one and only one instance of a class – Can you think of ever only wanting one instance of a class?"— Presentation transcript:

1 How Would You Solve This? l Suppose that you want to have one and only one instance of a class – Can you think of ever only wanting one instance of a class? »Lock manager? »One PubSub Bus instance l So, how? CS 3505 L19 - 1

2 Singleton Class Diagram l Explain how/why this works l Will this work for any time that you want to have one and only one instance of any class? CS 3505 L19 - 2

3 CS 3505 L19 - 3 Here Is Another Problem l Suppose that you have a set of sibling classes and then you want to optionally add other functionality

4 CS 3505 L19 - 4 Or How About This Problem? l Suppose that you have an object that changes periodically. Suppose that there are other objects (some or many) that want to watch and be notified of the changes.

5 CS 3505 L19 - 5 Design Patterns Some slides “borrowed” from: CS335 Univ of Arizona SYSC2004 Carlton University CS433-254 Univ of Melbourne

6 CS 3505 L19 - 6 Becoming a software designer l First learn the rules – Algorithms, data structures and languages l Then learn the principles – Structured design, OO design l However to truly master software design, you must study the design of masters – These designs have patterns to be understood, remembered and re-used l Implies DESIGN PATTERNS!!!

7 CS 3505 L19 - 7 What is good design? l 30 years ago, Christopher Alexander (an architect currently at UC Berkeley) asked – Are beauty and quality objective? »Can we agree some things are beautiful and some are not? – What makes a good architectural design? – What makes bad architectural design? – Can we recognize good design? – Is there an objective basis for such a judgment? – Is there a basis for describing common consensus l Alexander believed that beauty can be described through an objective basis that can be measured. l Examples: – Symmetry is good – Use half-round arches to support bridges and in doors. l Same equivalent ideas exist in software design

8 CS 3505 L19 - 8 Cultural Anthropology l Within a culture, individuals agree what is good design, what is beautiful l There are patterns in cultures that serve as objective bases for judging design l Proposed: The quality of software can be measured objectively – This is the idea behind design patterns – Patterns are not invented, they are recognized as elegant solutions that have been used many times

9 CS 3505 L19 - 9 Two Questions l Alexander asks – What is present in good quality design that is not present in a poor quality design? – What is present in poor quality design that is not present in a good quality design? l The task is to identify the things that make a design good and those that make a design bad l What are the commonalities in what is viewed as good (and what is viewed as bad) – A software system that is relatively easy to maintain is considered good »A fragile software system is considered bad – A software system that is easy to understand is considered good »obfuscated spaghetti code is bad

10 CS 3505 L19 - 10 Back to Architecture l Alexander observed many buildings, towns, streets, gardens, and pieces of furniture l Good constructs had things in common l They can be different but still of high quality – They may solve different problems – Consider a porch »A porch may be used to provide shade on a hot sunny day »Another porch provides a transition from the outside to the inside and from the inside to the outside l Did you ever live where there was no roof over the door?

11 CS 3505 L19 - 11 Can Solve the Same Problem in Different Ways l Or two different porches might solve the same problem in two different ways – Both may provide a pleasing way to enter or exit a house and still look different l Alexander was trying to identify and describe the consistency of quality in design – Having a transition from room to room or from inside to outside is important – Those transitions can take many forms

12 CS 3505 L19 - 12 Patterns l Alexander looked at different structures that solved the same problem l Found similarities between designs of high quality l Alexander called these similarities patterns l A pattern is a solution to a problem in a context l "Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice." –Christopher Alexander, A Pattern Language: Towns/Buildings/Construction, 1977

13 CS 3505 L19 - 13 Does this relate to Software? l Early 1990s software developers wondered if the same approach could be used in our discipline – Are there problems that occur over and over again that could be solved in somewhat the same way? – Could software be developed in terms of patterns, writing solutions after the pattern was identified? l People started looking for patterns l Then came one of the biggest selling books in CS...

14 CS 3505 L19 - 14 Gang of Four The GoF Book l The book with the greatest influence is Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. “Design Patterns: Elements of Reusable Object-Oriented Software”. Reading Mass. Addison Wesley, 1995. This book catalogs 23 patterns. l They offer advice and help to develop quality software l An object-oriented design pattern systematically names, explains and evaluates an important and recurring design in object-oriented systems

15 CS 3505 L19 - 15 Patterns in the GoF book l The Gang of Four did not invent the patterns l They found patterns that already existed in the software community – These are the similarities found in the design of software viewed to be of high quality – They made a rule to list three different systems that solved a problem in the same manner l Thousands of patterns have been written since – telecommunications patterns, Pedagogical patterns, analysis patterns, indexing patterns l Patterns have been called the next best software improvement since object-oriented programming.

16 CS 3505 L19 - 16 Why Study Patterns? l Can reuse solutions – Gives us a head start – Avoids the gotchas later (unanticipated things) – No need to reinvent the wheel l Establish common terminology – Design patterns provide a common point of reference l Provide a higher level perspective – Frees us from dealing with the details too early

17 CS 3505 L19 - 17 Other advantages l Most design patterns make software more modifiable, less brittle – We are using time tested solutions l Helps increase the understanding of basic object- oriented design principles – Encapsulation, inheritance, interfaces, polymorphism l Designs of large systems can avoid large inheritance hierarchies (there are alternatives)

18 CS 3505 L19 -18 Design Patterns l The idea of a pattern is fairly simple. – Represents a useful idea that can be reused in many context. l Patterns vary in structure, but they all contain similar kinds of information – This information helps us determine the whys and hows of the pattern

19 Design Pattern Information l Name: Should be evocative – So it is easy to recall a pattern l Intent: What this pattern tries to do l Motivation: Why this pattern exists – What problems does this solve l Documentation: How this pattern works – Examples a must l Applicability: Where this pattern is best used – and where is it maybe less effective CS 3505 L19 - 19

20 CS 3505 L19 - 20 Design Patterns l The exact format varies from pattern collection to collection – Lots of collections out there. l One major variation is a Anti-pattern approach – Describe a bad situation so it’s easy to recognize – Then, present the solution in pattern form that solves the current problem

21 CS 3505 L19 - 21 GoF Pattern Types l Creational Patterns – Deal with initializing and configuring classes and objects. l Structural Patterns – Deal with decoupling interface and implementation of classes and objects. l Behavioral Patterns – Deal with dynamic interactions among societies of classes and objects.

22 CS 3505 L19 - 22 Creational Patterns l Abstract Factory – Creates an instance of several families of classes l Builder – Separates object construction from its representation l Factory Method – Creates an instance of several derived classes l Prototype – A fully initialized instance to be copied or cloned l Singleton – A class of which only a single instance can exist – Ha!!!

23 CS 3505 L19 - 23 Structural Patterns l Adapter – Match interfaces of different classes l Bridge – Separates an object’s interface from its implementation l Composite – A tree structure of simple and composite objects l Decorator – Add responsibilities to objects dynamically l Façade – A single class that represents an entire subsystem l Flyweight – A fine-grained instance used for efficient sharing l Proxy – An object representing another object

24 CS 3505 L19 - 24 Decorator l Intent – Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. l Problem – You want to add behavior or state to individual objects at run-time. Inheritance is not feasible because it is static and applies to an entire class. l Example – The Decorator attaches additional responsibilities to an object dynamically. The ornaments that are added to pine or fir trees are examples of Decorators. Lights, garland, candy canes, glass ornaments, etc., can be added to a tree to give it a festive look. The ornaments do not change the tree itself which is recognizable as a Christmas tree regardless of particular ornaments used. As an example of additional functionality, the addition of lights allows one to "light up" a Christmas tree.

25 CS 3505 L19 - 25 Decorator l UML class diagram:

26 CS 3505 L19 - 26 Decorator

27 CS 3505 L19 - 27 Behavioral Patterns l Chain of Responsibility – A way of passing a request between a chain of objects l Command – Encapsulate a command request as an object l Interpreter – A way to include language elements in a program l Iterator – Sequentially access the elements of a collection l Mediator – Defines simplified communication between classes l Memento – Capture and restore an object's internal state l Observer – A way of notifying change to a number of classes l State – Alter an object's behavior when its state changes l Strategy – Encapsulates an algorithm inside a class l Template Method – Defer the exact steps of an algorithm to a subclass l Visitor – Defines a new operation to a class without change

28 CS 3505 L19 - 28 Observer l Intent – Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. l Problem – A large monolithic design does not scale well as new graphing or monitoring requirements are levied. l Example – The Observer defines a one-to-many relationship so that when one object changes state, the others are notified and updated automatically. Some auctions demonstrate this pattern. Each bidder possesses a numbered paddle that is used to indicate a bid. The auctioneer starts the bidding, and "observes" when a paddle is raised to accept the bid. The acceptance of the bid changes the bid price which is broadcast to all of the bidders in the form of a new bid.

29 CS 3505 L19 - 29 Observer l UML class diagram:

30 CS 3505 L19 - 30 Observer

31 Observer Sample // Create investors Investor s = new Investor("Sorros"); Investor b = new Investor("Berkshire"); // Create IBM and attach investors IBM ibm = new IBM("IBM", 120.00); ibm.Attach(s); ibm.Attach(b); // Change price, which notifies investors ibm.Price = 120.10; ibm.Price = 121.00; abstract class Stock { protected double price; private ArrayList investors = new ArrayList(); public void Notify() { foreach (Investor investor in investors) { investor.Update(this); } } // Properties public double Price { get { return price; } set { price = value; Notify(); } }... } CS 3505 L19 - 31

32 CS 3505 L19 - 32 When to use patterns l Solutions to problems that recur with variations. – No need to reuse if the problem occurs only once. l Solutions that require several steps. – Not all problems need all steps – Patterns can be an overkill is problems have simple solutions.

33 CS 3505 L19 - 33 When not to use Design Patterns l When applications that you build will not change… l Application code requirements are unique l Plenty of time to prototype your ideas l When other people don’t follow them!

34 CS 3505 L19 - 34 Benefits of Design Patterns l Enable large-scale reuse of software architecture l Explicitly capture expert knowledge and make it more widely available l Help improve developer communication

35 CS 3505 L19 - 35 Drawbacks to Design Patterns l Do not lead to direct code reuse l Are deceptively simple l Patterns may be overkill l Are validated by experience and discussion l Pattern integration is a human-intensive activity

36 CS 3505 L19 - 36 Summary l Roots in “real” architecture – Christopher Alexander l Well known solutions that work l Different patterns for different tasks l Design patterns help to achieve a flexible, maintainable and reusable software design l Keep pitfalls and drawbacks in mind! l http://www.dofactory.com/Patterns/Patterns.aspx http://www.dofactory.com/Patterns/Patterns.aspx – GoF patterns in C# with examples


Download ppt "How Would You Solve This? l Suppose that you want to have one and only one instance of a class – Can you think of ever only wanting one instance of a class?"

Similar presentations


Ads by Google