Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object-Orientated Analysis, Design and Programming

Similar presentations


Presentation on theme: "Object-Orientated Analysis, Design and Programming"— Presentation transcript:

1 Object-Orientated Analysis, Design and Programming
Presentation by Dr. Phil Legg Senior Lecturer Computer Science 8: Design Patterns Autumn 2016

2 What are Design Patterns?
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is a description or template for how to solve a problem that can be used in many different situations. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved.

3 Strategies for good OO design
Design to interfaces Favour aggregation over inheritance Find what varies and encapsulate it

4 Benefits of Design Patterns
Design patterns encourage code reuse and accommodate change by supplying well-tested mechanisms for delegation and composition, and other non-inheritance based reuse techniques. Design patterns can speed up the development process by providing tested, proven development paradigms Design patterns encourage more legible and maintainable code by following well-understood paths Reusing design patterns helps to prevent subtle issues that can cause major problems

5 Type of Design Patterns
Creational patterns : patterns provide instantiation mechanisms, making it easier to create objects in a way that suits the situation. Structural design patterns : generally deal with relationships between entities, making it easier for these entities to work together. Behavioural design patterns : patterns are used in communications between entities and make it easier and more flexible for these entities to communicate.

6 Creational Patterns This design patterns is all about class instantiation. Simplicity – some patterns make object creation easier so that clients will not contain large, complex code to instantiate an object Creational patterns are ones that create objects for you, rather than having you instantiate objects directly. This gives your program more flexibility in deciding which objects need to be created for a given case.

7 Structural Patterns These design patterns are all about Class and Object composition. How to compose classes and objects to form larger structures. A structural object pattern composes various objects to obtain new functionality; the Composite pattern is one example of this.

8 Behavioural Patterns Most of these design patterns are specifically concerned with communication between objects.

9 Factory Method Patterns
The factory related patterns are design patterns that allow for the creation of objects without specifying the type of object that is to be created in code. A factory class contains a method that allows determination of the created type at run-time.

10 Hotel Example Hotel Room +getPrice() Room rm; // if roomtype is single
rm = new Single(); // if roomtype is family rm = new Family(); Single Double Family +getPrice() +getPrice() +getPrice()

11 Duck Example

12 Problems with "new" When you use new you are certainly instantiating a concrete class, so that is an implementation and not an interface. Tying your code to a concrete class can make it more fragile and less flexible – when it comes time for changes or extensions, you'll have to reopen this code and examine what needs to be added (or deleted). By coding to an interface, you know you can insulate yourself from a lot of changes that might happen to a system in the future. If your code is written to an interface then it will work with any new classes implementing that interface through polymorphism.

13 Pizza - Example Suppose that you are required to develop a system that accepts orders for pizza. There are three types of pizza: cheese, Greek, and pepperoni. The pizzas differ according to the dough used, the sauce used, and the toppings. Draw a class diagram for the system.

14 Pizza - Example

15 Pizza - Example

16 Pizza - Example

17 Encapsulating Object Creation

18 Using a Simple Factory

19 Factory Factories handle the detail of object creation
Once we have a SimplePizzaFactory, our orderPizza() method just becomes a client of that object Any time it needs a pizza it asks the pizza factory to make one The orderPizza() method just cares that it gets a pizza!

20 SimplePizzaFactory

21 New SimplePizzaFactory
Why is this better? SimplePizzaFactory may have many clients. By encapsulating the pizza creating in one class, we now only have one place to make modifications when the implementation changes.

22 Simple Factory Pattern
Intent Creates objects without exposing the instantiation logic to the client Referes to the newly created object through a common interface Implementation

23 Facade Pattern Intent: You want to simplify how to use an existing system. You need to define your own interface. Problem: You need to use only a subset of a complex system, or you need to interact with the system in a particular way. Solution: The Façade presents a new simplified interface for the client of the existing system, to make it easier to use. Implementation: Define a new class that has the required interface, and have this new class use the existing system.

24 Example – Home Theatre DVD Player Projection video system
Automated screen Surround sound Popcorn maker!

25 Example – Home Theatre

26 Adding a Facade

27 Home Theatre Facade

28 Watching a Movie using Facade

29 Façade Pattern - Discussion
If a client has to interact directly with a number of objects in a related set of objects, it will lead to increased coupling and added complexity for the client Create a façade object whose methods provide the required functionality interface of the related set of objects. Client objects then interact with the façade object. Limiting the knowledge of the client to the façade object would allow using all the other objects but would lead to less coupling and therefore a simpler client.

30 Façade Pattern – When to Use
Façade Patterns apply when you do not need to use all the functionality of a complex system, and can create a new class that contains all the rules for accessing that system. You want to encapsulate or hide the original system You want to use the functionality of the original system and want to add some new functionality as well. The cost of writing this new class is less than the cost of everybody learning how to use the original system or is less than you would spend on maintenance in the future.

31 Principle of Least Knowledge
The Principle of Least Knowledge (PLK) guides us to reduce the interactions between objects to just a few close "friends" This principle prevents us from creating designs that have a large number of classes coupled together so that changes in one part of the system cascade to other parts When you build a lot of dependencies between many classes, you are building a fragile system that will be costly to maintain and cmplex for others to understand

32 Façade and PLK

33 Adapter Pattern A Structural pattern
Convert the interface of a class into another interface that the client expects. Adapter lets classes work together that could not otherwise do so, because of incompatible interfaces. (Essentially, we need a way to create a new interface for an object that does the right stuff but has the wrong interface).

34 Adapter Pattern Intent: Match an existing object beyond your control to a particular interface Problem: A system has the right data and behaviour but the wrong interface Solution: Define an adapter class which acts as an intermediary. The adapter does little work itself but merely translates commands from one form to another. Implementation: Contain the existing class in another class. Have the containing class match the required interface and call the methods of the containing class.

35 Adapter Pattern – When to Use
The Adapter pattern enables a system to use classes whose interfaces don't quite match its requirements Especially useful for off-the-shelf code, for toolkits, and for libraries.

36 Adapter Pattern - Example
interface Shape { ​   void drawRec(int x1, int y1, int x2, int y2); ​ }​ class LegacyRectangle { ​   public void drawRec(int x, int y, int w, int h) {   ​     println("rectangle" + x + ',' + y)​     println("with width " + w + " and height " + h); ​   } ​ }

37 Adapter Pattern - Example
class RectangleAdapter implements Shape { ​   private LegacyRectangle adaptee = ​                       new LegacyRectangle(); ​   public void drawRec(int x1, int y1, int x2, int y2) { ​    adaptee.drawRec( ​         x1,y1,Math.abs(x2-x1), Math.abs(y2-y1)); ​   } ​ }

38 Adapter Pattern - Exercise
Write a client that would use the RectangleAdapter to draw a rectangle.

39 Adapter Pattern - Example
public class ShapeBuilding { public static void main(String [] args){ RectangleAdapter rectangle= new RectangleAdapter(); int topx=10, topy=10; int bottomx=110,bottomy=30; rectangle.drawRec(topx,topy, bottomx,bottomy); }

40 Composition vs Inheritance
Object-Orientated Programming (OOP) has two well known candidates for the reuse of functionality: inheritance (white box) and composition (black box) If you try to reuse code by inheriting from a class you will make the subclass dependent on the parent class. This makes the system unnecessarily complex, less testable and makes the exchange of functionality at run time unnecessarily hard. Composition means that one class uses another. You will further promote decoupling by defining the interfaces clearly. That will also give the advantage that implementations can be easily replaced.

41 Decorator Pattern The decorator pattern attaches additional responsibilities to an object dynamically Decorators provide a flexible alternative to subclassing for extending functionality.

42 Starbuzz Coffee

43 Starbuzz Coffee What if each combination of drink was treated as a individual entity? Inheritance structure leads to a poor design for this example...

44 Decorator Pattern for Starbuzz
Instead of using inheritance, we'll start with a beverage and "decorate" it with extras at runtime. For example, a Dark Roast with Mocha and Whip could be: Take a DarkRoast object Decorate it with a Mocha object Decorate it with a Whip object Call the cost() method and rely on delegation to add on the extras

45 Decorating the Beverages

46 Coding the Beverages

47 Coding the Beverages

48 Coding the Beverages

49 Testing our Starbuzz Code

50 Decorator Pattern - Discussion
This pattern is designed so that multiple decorators can be stacked on top of each other, each time adding a new functionality to the overridden method(s) Decorators and the original class object share a common set of features. The decorator pattern is an alternative to subclassing. Subclassing adds behaviour at compile time, and the change affects all instances of the original class; decorating can provide new behaviour at run-time for individual objects.

51 Summary Types of design patterns – creational, structural, behavioural
Factory Methods Façade Adaptor Decorator


Download ppt "Object-Orientated Analysis, Design and Programming"

Similar presentations


Ads by Google