Presentation file
Design Patterns and princibles.ppt
Presentation content
Agenda
- What are design principles?
- What are design patterns?
- Design patterns benefits and problems
- History of patterns
- Design patterns categories
- Design patterns catalogue
- MVC “a compound pattern”
- Are these all the patterns we have?
- Should i follow design patterns/principles strictly?
What are design principles?
A set of principles that guide you during your design
Ex: “Favor composition over inheritance”
What are design patterns?
A pattern is a solution to a problem in a context
Context
Is a situation in which the pattern applies. This should be recurring situation (ex: you have a collection of objects )
Problem
Refer to the goal you are trying to achieve in this context, but also refers to any constraints that occur in the context (ex: you need to step through them without exposing their implementation )
Solution
Is what you are after: a general design that anyone can apply which resolves the goal and set of constraints (ex: encapsulate the iteration into a separate class )
It is a proven design experience that can be used to avoid common mistakes
Design patterns benefits and problems
Benefits
A guaranteed solution that is used and tested by lots of developers
Using a solutions that is well documented and that other developers are going to recognize (shared vocabulary)
Problems
Increase complexity: Design pattern often introduce additional classes and objects to your design
Decrease efficiency: Adding more layers to your design
Some times there are much simpler solutions to solve the same problem
History of patterns
Patterns originated as an architectural concept by Christopher Alexander.[3]
In 1987, Kent Beck and Ward Cunningham began experimenting with the idea of applying patterns to programming and presented their results at the OOPSLA conference that year.[3]
Design patterns gained popularity in computer science after the book “Design Patterns: Elements of Reusable Object-Oriented Software” was published in 1994 (Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides) (GOF). [3]
Be proud :)
John Vlissides is a researcher at the IBM T.J. Watson Research Center. [2]
Richard Helm was in the Software Technology department at IBM T.J. Watson Research Center investigating object-oriented design and reuse and visualization. Recently rejoined IBM to start the Australian branch of the Object Technology Practice. [2]
Design patterns categories
Patterns are categorized according to their purposes
Creational
Involve object instantiation and all provide a way to decouple a client from the objects it needs to instantiate.
Behavioral
Is concerned with how classes and objects interact and distribute responsibilities
Structural
Structural patterns describe how classes and objects can be combined to form larger structures
Class patterns
Describe how relationships between classes are defined via inheritance.
Relationships in class patterns are established at compiler time.
Object patterns
Describe relationships between objects and are primarily defined by composition.
Relationships in object patterns are typically crated at runtime and are more dynamic and flexible.
Design patterns categories
Design patterns catalogue
1- Factory pattern
Simple Factory (not a pattern)
Simple factory UML [12]
Design patterns catalogue
1- Factory pattern
Abstract factory pattern
Definition:
Provide an interface for creating families of related or dependant objects without specifying their concrete classes
Problem
A system should be independent of how its products are created, composed and represented
A family of related product objects is designed to be used together, and you need to enforce this constraint
Design patterns catalogue
1- Factory pattern - Abstract factory pattern - Solution
Pattern generic UML [10]
Design patterns catalogue
1- Factory pattern - Abstract factory pattern - Solution
Real world example
Design patterns catalogue
1- Factory pattern
Factory method pattern
Definition:
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to the subclass
Problem
A class can't anticipate the class of the objects it must create
Need to delegate responsibility to helper subclasses
Design patterns catalogue
1- Factory pattern - Factory method pattern - Solution
Pattern generic UML [4]
Design patterns catalogue
1- Factory pattern
Design principles
Dependency Inversion principle: Depend upon abstraction. Do not depend upon concrete classes (height level class depend on abstraction and low level classes depend on abstraction…they don’t depend on each other )
It helps decoupling high level and low level classes
Benefits/consequences
+ Flexibility: removes type dependencies from clients
+ Code is made more flexible and reusable by the elimination of instantiation of
application-specific classes
- Supporting new kinds of products requires changing the AbstractFactory
interface
Design patterns catalogue
2- Builder pattern
Definition:
Separate the construction of a complex object from its representation so that the same construction process can create different representations.
[it is a factory of complex objects ]
Problem
You need to encapsulate the construction of a product and allow it to be constructed in steps.
Design patterns catalogue
2- Builder pattern – Solution
Design patterns catalogue
2- Builder pattern – Solution
Design patterns catalogue
2- Builder pattern
Benefits/consequences
+ Encapsulate the way complex objects is constructed
+ Allow objects to be constructed in a multistep and varying process (as opposed to one step factories)
+ Hides the internal representation of the product from the client
+ Product implementation can be swapped in and out because the client only sees an abstract interface
- Constructing objects requires more domain knowledge of the client than using a Factory
Design patterns catalogue
3- Prototype pattern
Definition
Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype
Problem
You are creating an instance of a given class that is either expensive or complicated
Design patterns catalogue
3- Prototype pattern – Solution
Design patterns catalogue
3- Prototype pattern – Solution
Design patterns catalogue
3- Prototype pattern – Solution
Design patterns catalogue
3- Prototype pattern
Benefits/consequences
+ Hides the complexities of making new instances from the client
+ Provide the option for the client to generate objects whose type is not known
+ In some circumstances, copying an object can be more efficient than creating a new object
- making a copy of an object can sometimes be complicated
Design patterns catalogue
4- Singleton pattern
Definition:
Ensure a class only has one instance and provide a global point of access to it
Problem
When there must be exactly one instance of a class, and it must be accessible from a well-known access point
Design patterns catalogue
Pattern generic UML [7]
Design patterns catalogue
4- Singleton pattern – Solution
Design patterns catalogue
4- Singleton pattern
Benefits/consequences
+ Reduces namespace pollution
+ Eliminates the need for global variables that store single instances
+ Allow extension by subclassing
- Implementation may be less efficient than a global
Used in
WindowManager, PrinterManager, FileManager, SecurityManager, ...
Log and error reporting classes
Design patterns categories
Design patterns catalogue
5- Adapter pattern
Definition:
Converts the interface of a class into another interface clients expect. Lets classes work together that couldn’t otherwise because of incompatible interface
Problem
You want to use an existing class, and its interface does not match the one you need
Design patterns catalogue
5- Adapter pattern – Solution - Object adapter
Pattern generic UML [4]
Design patterns catalogue
5- Adapter pattern – Solution - Class adapter
Pattern generic UML [15]
Design patterns catalogue
5- Adapter pattern
Benefits/consequences
+ Allows for pre-existing objects to fit into new class structures without being limited by their interfaces
- Makes it harder to override Adaptee behavior, It will require subclassing Adaptee and making Adapter refer to the subclass rather than the Adaptee itself
Design patterns catalogue
6- Bridge pattern
Definition:
Decouple an abstraction from its implementation so that the two can vary independently
Problem
You need to vary an interface and an implementation in different ways
Design patterns catalogue
6- Bridge pattern – Solution
Design patterns catalogue
6- Bridge pattern – Solution
Design patterns catalogue
6- Bridge pattern
Benefits/consequences
+ Decouple an implementation so that it is not bound permanently to an interface
+ Abstraction and implementation can be extended independently
+ Changes to the concrete abstraction don’t affect the client
- Increase complexity
Used in
Graphic and windowing systems that need to run over multiple platforms.
Design patterns catalogue
7- Composite pattern
Definition:
Compose object into tree structures to represent part-whole (tree made of parts but treated as a whole) hierarchies. Composite lets client treat individual objects and compositions of objects uniformly
Problem
You want to represent part-whole hierarchies of objects
You want clients to be able to ignore the difference between compositions of objects and individual objects
Design patterns catalogue
7- Composite pattern – Solution
Design patterns catalogue
7- Composite pattern – Solution
Design patterns catalogue
7- Composite pattern
Benefits/consequences
+ Uniformity: treat components the same regardless of complexity
+ Extensibility: new Component subclasses work wherever old ones do
- Can make your design overly general – Harder to restrict the components of a composite
Design patterns catalogue
8- Decorator pattern
Definition:
The decorator pattern allows new/additional behavior to be added to an existing method of an object dynamically.
Subclassing adds behaviour at compile time whereas decorators provide a new behaviour at runtime.
Problem
Need to add responsibilities to objects dynamically and transparently
Design patterns catalogue
8- Decorator pattern
Problem
Real world example [9]
Design patterns catalogue
8- Decorator pattern - Solution
Pattern generic UML [9]
Design patterns catalogue
8- Decorator pattern – Solution
Pattern generic UML [4]
Design patterns catalogue
8- Decorator pattern
Design principles
Classes should be open for extension but closed for modification
To keep “reliable tested code” away from altering and in the same time allow to extends your code
Benefits/consequences
+ More flexible than static inheritance
+ Responsibilities can be added/removed at run-time
+ Avoids subclass explosion
- Lots of little objects
- Overuse can be complex (many decorators)
Used in
Used in java IO ( BufferedOutputStream )
Design patterns catalogue
9- Facade pattern
Definition:
Provides a unified interface to set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
Problem
Need to provide a simple interface to a complex system
Need to decouple a subsystem from its clients
Need to provide an interface to a software layer
Design patterns catalogue
9- Facade pattern – Solution
Pattern generic UML [4]
Design patterns catalogue
9- Facade pattern – Solution
Design patterns catalogue
9- Facade pattern
Benefits/consequences
+ Promotes weak coupling between the subsystem and its clients
- One possible disadvantage to this pattern is that you may lose some functionality contained in the lower level of classes
Design patterns catalogue
10- Flyweight pattern
Definition:
Flyweight is a structural pattern which use sharing to support large numbers of small objects efficiently
Problem
An application uses a large number of objects.
Storage costs are high because of the sheer quantity of objects.
Most object state can be made extrinsic [that is, the object state that can be defined outside the object itself.]
Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed.
Design patterns catalogue
10- Flyweight pattern – Solution
Design patterns catalogue
10- Flyweight pattern
Benefits/consequences
+ Reduce number of objects instances at runtime, saving memory.
+ Centralize state for many virtual objects into a single location
- Once implemented single logical instances of the class will not be able to behave independently from the other instances.
Design patterns catalogue
11- Proxy pattern
Definition:
Provide a surrogate (alternative) or placeholder for another object to control access to it.
Problem
Use the proxy pattern to create a representative object that controls access to another object, which may be remote, expensive to create or in need of securing
Design patterns catalogue
11- Proxy pattern – Solution
Design patterns catalogue
11- Proxy pattern – Other kinds of proxy patterns
Remote proxies
Responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space. (RMI)
Virtual proxies
Controls access to an object that is expensive to instantiate ( wait …loading image)
Protection proxies
Controls access to the methods of an object based on the caller
Other types
Cashing, synchronization, firewall, copy-on-write proxies.
Design patterns catalogue
11- Proxy pattern
Benefits/consequences
Remote Proxy
Hides fact that object resides in a different address space.
Virtual Proxy
Perform optimizations such as creation on demand.
Protection Proxy
Allow additional housekeeping tasks when object is accessed.
Used in
Distributed systems
Protection proxy pattern used in java: java.lang.reflect package
Design patterns categories
Design patterns catalogue
12- Chain of responsibility pattern
Definition:
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
Problem
Use the chain of responsibility pattern when you want to give more than one object a chance to handle a request
Design patterns catalogue
12- Chain of responsibility pattern – Solution
Design patterns catalogue
12- Chain of responsibility pattern – Solution
Design patterns catalogue
12- Chain of responsibility pattern
Benefits/consequences
+ Decouple the sender of the request from its receiver
+ Simplifies your object because it doesn’t have to know the chain structure and keep direct references to its members
+ Allow you to add or remove responsibilities dynamically by changing the members or order of the chain
Hard to observe runtime characteristics and debug
Used in
Used in windows systems to handle events like mouse clicks and keyboard events
Design patterns catalogue
13- Command pattern
Definition:
Encapsulate a request as an object , there by letting you parameterize clients with different requests , queue or log requests, and support undoable operations
Problem
Parameterize objects by an action to perform.
Specify, queue, and execute requests at different times
Support undo
Support logging changes so that they can be reapplied in case of a system crash.
Design patterns catalogue
13- Command pattern - Solution
Pattern generic UML [4]
Design patterns catalogue
13- Command pattern – Solution
Design patterns catalogue
13- Command pattern – Solution
Design patterns catalogue
13- Command pattern
Benefits/consequences
+ Decouples an object, making a request from the one that knows how to perform it (invoker, receiver)
- The major disadvantage of the pattern is that it results in lots of little Command classes that can increase design complexity
Used in
Logging, transactional systems, Queuing
Design patterns catalogue
14- Interpreter pattern
Definition:
Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language
Problem
You want to build an interpreter for a simple language
Design patterns catalogue
14- Interpreter pattern – Solution
Design patterns catalogue
14- Interpreter pattern
Benefits/consequences
+ Representing each grammar rule in a class makes the language easy to implement, extend
+ Centralize state for many virtual objects into a single location
- It can become cumbersome when the number of grammar rules is large. In these cases a parser/compiler generator may be more appropriate
Design patterns catalogue
15- Iterator pattern
Definition:
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
Problem
Require multiple traversal algorithms over an aggregate
Require a uniform traversal interface over different aggregates
When aggregate classes and traversal algorithm must vary independently
Design patterns catalogue
15- Iterator pattern – Solution
Design patterns catalogue
15- Iterator pattern
Design principles
Single responsibility: a class should have only one reason to change
It promotes high cohesion
Having more than one responsibility increase the probability that the class will change in the future
Benefits/consequences
+ Flexibility: aggregate and traversal are independent
+ Multiple iterators multiple traversal algorithms
+ Removed the responsibility of traversal from the aggregate class
- Additional communication overhead between iterator and aggregate
Used in:
Used in java (Iterator interface and the collections framework)
Design patterns catalogue
16- Mediator pattern
Definition:
Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently
Problem
You want to centralize complex communications and control between related objects
Design patterns catalogue
16- Mediator pattern – Solution
Design patterns catalogue
16- Mediator pattern – Solution
Design patterns catalogue
16- Mediator pattern – Solution
Design patterns catalogue
16- Mediator pattern
Benefits/consequences
+ Increase the reusability of the objects supported by the mediator by decoupling them from the system
+ Simplifies maintenance of the system by centralizing control logic
+ Simplifies messages sent between objects in the system
- Without proper design the mediator itself can become complex
Used in
Used to coordinate related GUI components
Design patterns catalogue
17- Memento pattern
Definition
Meaning: A reminder of the past; a keepsake [dictionary.com]
Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later
Problem
You need to be able to return an object to one of it’s previous states (ex: save a game state)
Design patterns catalogue
17- Memento pattern – Solution
Design patterns catalogue
17- Memento pattern – Solution - code
Design patterns catalogue
17- Memento pattern
Benefits/consequences
+ Keeping the saved state external from the key object helps maintain cohesion
+ Keep the key object’s data encapsulated
+ Provide easy to implement recovery capability
- Saving and restoring can be time consuming
Used in
Used in Game programming
Design patterns catalogue
18- Observer pattern
Definition:
Defines a one-to-many dependency between objects so that when one object changes state, all of its dependency are notified and updated automatically
Problem
When a change to one object requires changing others, and you don't know how many objects need to be changed
Design patterns catalogue
18- Observer pattern - Problem
Real world example [34]
Design patterns catalogue
18- Observer pattern - Solution
Pattern generic UML [4]
Design patterns catalogue
18- Observer pattern
Design principles
Strive for loosely coupled designs between objects that interact
Change in either parts will not affect the other part
Benefits/consequences
+ Modularity: subject and observers may vary independently
+ Extensibility: can define and add any number of observers
- High Costs for update: Several consecutive operations may cause several consecutive updates, which may cause extremely high costs for update.
Used in
Java has several implementations of the observable pattern including java.util.Observable implementation
Swing makes heavy use of the observer pattern
MVC uses this pattern
Design patterns catalogue
19- State pattern
Definition:
Allow an object to alter its behavior when it’s internal state changes. The object will appear to change it’s class
Problem
An object’s behavior depends on its state, and it must change its behavior at run-time depending on that state.
Operations have large, multipart conditional statements that depend on the object’s state.
Design patterns catalogue
19- State pattern – Solution
Design patterns catalogue
19- State pattern – Solution
Design patterns catalogue
19- State pattern
Benefits/consequences
+ It localizes state-specific behavior (we localized any change that will be made) and partitions behavior for different states.
+ State objects can be shared among context instances
- It will result in a greater number of classes in your design
Design patterns catalogue
20- Strategy pattern
Definition:
The strategy pattern is a particular software design pattern, whereby algorithms can be selected on-the-fly at runtime depending on conditions, like strategies in a war situation.
Problem
When an object should be configurable with one of several algorithms
A class defines many behaviors.
Design patterns catalogue
20- Strategy pattern – Solution
Pattern generic UML [4]
Design patterns catalogue
20- Strategy pattern
Design principles
Encapsulate what varies
Extendibility and maintainability
Favor composition over inheritance
Extendibility, change at runtime
Program to interfaces, not implementation
Extendibility, change at runtime
Benefits/consequences
+ Greater flexibility, reuse, extendibility
+ Can change algorithms dynamically
- Strategy creation & communication overhead
- Increase the number of classes in the design
Design patterns catalogue
21- Template pattern
Definition:
Define the skeleton of an algorithm in an operation, deferring some steps to subclass. Template method lets subclasses refine certain steps of an algorithm without changing the algorithm’s structure
Problem
To implement invariant aspects of an algorithm once and let subclasses define variant parts
To localize common behaviour in a class to increase code reuse
Design patterns catalogue
21- Template pattern – Solution
Pattern generic UML [4]
Design patterns catalogue
21- Template pattern – Solution
Design patterns catalogue
21- Template pattern
Design principles
Hollywood principle: Don’t call us we will call you (high level say to low level components)
This principle allows low level components to hook themselves into a system, but high level components determine when they are needed and how
Reduce object dependencies in your systems (one call to processOrder)
Insulate the application from the specific underlying implementation
Make your code more portable
Benefits/consequences
+ Leads to inversion of control (“Hollywood principle”: don't call us – we'll call you)
+ Promotes code reuse
+ Lets you enforce overriding rules
- Problem of verification of the assumptions made by the base class which can be violated by the implementation in a subclass.
Design patterns catalogue
22- Visitor pattern
Definition
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates
Problem
You want to add capabilities to a composite of objects and encapsulation is not important
Design patterns catalogue
22- Visitor pattern
– Solution
Design patterns catalogue
22- Visitor pattern
Benefits/consequences
+ Allow you to add operations to a composite structure without changing the structure itself
+ Adding new operations is relatively easy
- The composite class encapsulation is broken when the visitor is used
MVC “a compound pattern”
Patterns can be used together
MVC is a compound pattern consisting of the observer (model), Strategy (controller) and Composite pattern (view)
MVC “a compound pattern”
MVC “a compound pattern”
Are these all the patterns we have?
The 23 patterns in this presentation are the fundamental patterns found in GOF book; there are other categories of patterns such as
Domain-specific patterns (real-time and concurrent systems, j2EE)
Business process patterns
User interface patterns
Organizational patterns ( describe the structure and practiced of human organization )
Application patterns (pattern for creating system level architecture )
Are these all the patterns we have?
Should i follow design patterns/principles strictly?
Off course not, Design Patterns and principles are not meant to be laws and rules; they are guidelines that you can alter to fit your needs
Patterns are not set in stone; adapt and tweak them to meet your needs
References
http://www.cmcrossroads.com/bradapp/docs/patterns-intro.html
http://hillside.net/patterns/DPBook/GOF.html
http://en.wikipedia.org/wiki/Design_pattern_(computer_science)
http://www.dofactory.com/Patterns/Patterns.aspx
http://home.earthlink.net/~huston2/dp
http://sern.ucalgary.ca/courses/seng/443/f2004/patternNotes/Hanna_Tseng_&_Xing/
http://www.ece.uwaterloo.ca/~talguind/ ece355/project/DPATTERNS-OVERVIEW-EXAMPLES.ppt
http://www.cs.clemson.edu/~malloy/courses/patterns/
http://cs.anu.edu.au/student/comp2110/archive-2002/lectures/lec20/lec20.html
http://weblogs.pontonetpt.com/rjclaro/gallery/image/246.aspx
http://people.cs.uchicago.edu/~mark/51023/presentations/Abstract%20Factory.ppt
http://builder.com.com/5100-6386-1045719.html
http://www.research.umbc.edu/~tarr/dp/lectures/Factory-2pp.pdf
http://www.codeproject.com/csharp/commandpatterndemo.asp
http://cs.anu.edu.au/student/comp2110/archive-2002/lectures/lec19/lec19.html
http://www.macromedia.com/devnet/flashremoting/articles/facades.html
http://csse.usc.edu/classes/cs377_2004/Lecture13.ppt
http://www.csc.calpoly.edu/~dbutler/tutorials/winter96/patterns/tutorial.html
http://bdn.borland.com/borcon2004/article/paper/0,1963,32140,00.html
http://www-sop.inria.fr/axis/cbrtools/usermanual-eng/Patterns/Template.html
http://www.cse.wustl.edu/~cdgill/courses/cse432/Composite_Presentation_1_30.ppt
http://vlib.eitan.ac.il/dp/composite.html
http://www.cs.purdue.edu/homes/apm/slides/uml-slides/sundar-patterns-2.ppt
http://hermanland.com:8000/ouhk/mt356/herman2002/unit3/ar01s08.html
http://www.eli.sdsu.edu/courses/spring98/cs635/notes/proxy/proxy.html
http://www.cse.wustl.edu/~cdgill/courses/ cse432/Proxy_Observer_Presentation.ppt
http://webml.org/webml/page108.do;jsessionid=aZaO9iNGx_x-?dau92.oid=45&UserCtxParam=0&GroupCtxParam=0
http://publib.boulder.ibm.com/infocenter/iadthelp/topic/com.ibm.etools.struts.doc/topics/cstrdoc001.html
http://hermanland.com:8000/ouhk/mt356/herman2002/unit4/ar01s07.html
http://www.caterpillar.onlyfun.net/Gossip/DesignPattern/DesignPattern.htm
http://www.javaworld.com.tw/jute/post/view?bid=25&id=12509&sty=1&tpg=1&age=-1
http://people.cs.uchicago.edu/~matei/TA/CSPP523/memento.ppt
Head First Design Patterns Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra. 2004.. O'Reilly Media.
Design Patterns: Elements of Reusable Object-Oriented Software”, Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides) (GOF), 1994, Addison Wesley
Tweet
No comments:
Post a Comment