Presentation is loading. Please wait.

Presentation is loading. Please wait.

How Would You Solve This?

Similar presentations


Presentation on theme: "How Would You Solve This?"— Presentation transcript:

1 How Would You Solve This?
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  So, how? CS 3505

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

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

4 Or How About This Problem?
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. CS 3505

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

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

7 What is good design? 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 Alexander believed that beauty can be described through an objective basis that can be measured. Examples: Symmetry is good Use half-round arches to support bridges and in doors. Same equivalent ideas exist in software design CS 3505

8 Cultural Anthropology
Within a culture, individuals agree what is good design, what is beautiful There are patterns in cultures that serve as objective bases for judging design 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 CS 3505

9 Two Questions 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? The task is to identify the things that make a design good and those that make a design bad 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 CS 3505

10 Back to Architecture Alexander observed many buildings, towns, streets, gardens, and pieces of furniture Good constructs had things in common 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 Did you ever live where there was no roof over the door? CS 3505

11 Can Solve the Same Problem in Different Ways
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 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 CS 3505

12 Patterns Alexander looked at different structures that solved the same problem Found similarities between designs of high quality Alexander called these similarities patterns A pattern is a solution to a problem in a context "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 CS 3505

13 Does this relate to Software?
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? People started looking for patterns Then came one of the biggest selling books in CS... CS 3505

14 Gang of Four The GoF Book
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, This book catalogs 23 patterns. They offer advice and help to develop quality software An object-oriented design pattern systematically names, explains and evaluates an important and recurring design in object-oriented systems CS 3505

15 Patterns in the GoF book
The Gang of Four did not invent the patterns 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 Thousands of patterns have been written since telecommunications patterns, Pedagogical patterns, analysis patterns, indexing patterns Patterns have been called the next best software improvement since object-oriented programming. CS 3505

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

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

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

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

20 Design Patterns The exact format varies from pattern collection to collection Lots of collections out there. 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 CS 3505

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

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

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

24 Decorator Intent Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. 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. 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. CS 3505

25 Decorator UML class diagram: CS 3505

26 Decorator CS 3505

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

28 Observer Intent Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Problem A large monolithic design does not scale well as new graphing or monitoring requirements are levied. 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. CS 3505

29 Observer UML class diagram: CS 3505

30 Observer CS 3505

31 Observer Sample 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();   } } ... } // Create investors Investor s = new Investor("Sorros"); Investor b = new Investor("Berkshire"); // Create IBM and attach investors IBM ibm = new IBM("IBM", ); ibm.Attach(s); ibm.Attach(b); // Change price, which notifies investors ibm.Price = ; ibm.Price = ; CS 3505

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

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

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

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

36 Summary Roots in “real” architecture Christopher Alexander
Well known solutions that work Different patterns for different tasks Design patterns help to achieve a flexible, maintainable and reusable software design Keep pitfalls and drawbacks in mind! GoF patterns in C# with examples CS 3505


Download ppt "How Would You Solve This?"

Similar presentations


Ads by Google