design patterns module name - object oriented modeling by archana munnangi s r kumar utkarsh batwal...
Post on 22-Dec-2015
214 views
TRANSCRIPT
Design PatternsDesign Patterns
Module Name - Object Oriented Modeling
By
Archana Munnangi S R Kumar Utkarsh Batwal (17040771) (17040037) (17040842)
What are Design What are Design Patterns ?Patterns ?
It addresses a problem that occurs It addresses a problem that occurs repeatedly in a variety of contexts and repeatedly in a variety of contexts and suggests the solution to the problem.suggests the solution to the problem.
Pattern ElementsPattern Elements Pattern NamePattern Name ProblemProblem SolutionSolution ConsequencesConsequences
Design Pattern SpaceDesign Pattern Space
Purpose – Reflects what a pattern does. Patterns can have either a Creational, Structural or Behavioral purpose
Scope – Specifies whether the pattern applies primarily to the Classes or to the Objects
Purpose
Creational Structural Behavioral
Scope Class Factory Method Adapter Method InterpreterTemplate Method
Object Abstract FactoryBuilder
PrototypeSingleton
AdapterBridge
CompositeDecorator
FaçadeFlyweight
Proxy
Chain of ResponsibilityCommand
IteratorMediatorMementoObserver
StateStrategyVisitor
Creational PatternCreational Pattern
Abstract the instantiation processAbstract the instantiation process Separate the system from object Separate the system from object
creationcreation Encapsulate information about concrete Encapsulate information about concrete
classes in the systemclasses in the system Hide how instances are createdHide how instances are created
Examples : Factory Method, Examples : Factory Method, Abstract Abstract Factory, Builder, Factory, Builder, PrototypePrototype, Singleton, Singleton
Prototype (Creational Pattern)Prototype (Creational Pattern)
Intent Intent - - Specify the kinds of objects to create Specify the kinds of objects to create using a prototypical instance, and create new using a prototypical instance, and create new objects by copying this prototype.objects by copying this prototype.
Hides complexities of making new instances from the client
In some cases copying an existing object can be more efficient than creating a new object.
Provides the option for client to generate objects whose type is not known.
Example of a Prototype Pattern - Mitotic Cell Division in animal cells. The Animal cell corresponds to the Prototype, as it has an “interface” for cloning itself
A specific instance of a cell corresponds to the ConcretePrototype
Prototype pattern in the original cell takes an active role in creating a new instance of itself
Sample code to clone an Animal cell
public class SingleCellOrganism {public static void main(String[] args){AnimalCell cell = new AnimalCell(); // create a cloneAnimalCell newAnimalCell = (AnimalCell)cell.split();}}// End of class
Here split() implements the clone() function in the Animal cell
Use of Prototype –Use of Prototype – In Complex hierarchies prototype should be In Complex hierarchies prototype should be
considered for creating new object of many considered for creating new object of many typestypes
Consequences –Consequences – Add/Remove products at runtimeAdd/Remove products at runtime Specifying new object by varying objectsSpecifying new object by varying objects Specifying new object by varying structureSpecifying new object by varying structure Reduced subclassingReduced subclassing
DisadvantagesDisadvantages – – Making a copy of the objects is sometimes Making a copy of the objects is sometimes
very complicated.very complicated.
Structural PatternStructural Pattern
Structural patterns describe how classes Structural patterns describe how classes and objects can be combined to form larger and objects can be combined to form larger structures. structures.
Structural Structural classclass patterns use inheritance to patterns use inheritance to compose Interfaces or Implementations.compose Interfaces or Implementations.
Structural Structural object object patterns define ways to patterns define ways to compose objects to obtain new compose objects to obtain new functionality. functionality.
Examples : Adapter , Bridge, Composite, Examples : Adapter , Bridge, Composite, DecoratorDecorator, Facade, Flyweight, Proxy, Facade, Flyweight, Proxy
Decorator (Structural Pattern)Decorator (Structural Pattern) Intent Intent – Attach additional responsibilities to an object – Attach additional responsibilities to an object
dynamically. Provide a flexible alternative to dynamically. Provide a flexible alternative to subclassing for extending functionality . They are also subclassing for extending functionality . They are also known as Wrapper.known as Wrapper.
A set of decorator classes are used to wrap the Concrete (core) components.
Decorators change the properties of the Concrete components by adding new functionality.
Follows the Open-Close design principle
Example of Decorator patternExample of Decorator pattern : :
Use Inheritance?
Problem with Inheritance !!!!
Solution – Design Principle – The Classes must be open for extension but closed for modification.
Solution :
Sample Code for Cost Implementation of CoffeaArabia Sample Code for Cost Implementation of CoffeaArabia with Mochawith MochaTotal Cost = 59 + 39 = 98 Rupees
Use of Decorator –
Add/Withdraw responsibilities to/from the individual objects dynamically
When extension by subclassing is impractical
Consequences – Flexibility Offers a “pay as you go” approach Decorators and its component are not identical Lots of little objects are created
DisadvantagesDisadvantages – – May add many classes, makes package hard to
understand─ Like I/O streams
Creating new objects could be more complex
Behavioral PatternBehavioral Pattern
Deals with the algorithms and the assignment Deals with the algorithms and the assignment of responsibilities between the objectsof responsibilities between the objects
Behavioral Behavioral classclass patterns use inheritance to patterns use inheritance to describe algorithms and flow of control describe algorithms and flow of control between classes. between classes.
Behavioral Behavioral objectobject pattern use the composition pattern use the composition of objects to perform some task that no single of objects to perform some task that no single object can perform alone. object can perform alone.
Examples : Examples : Chain of Responsibility, Command, Chain of Responsibility, Command, Iterator, Mediator, Memento, Observer, State, Iterator, Mediator, Memento, Observer, State, StrategyStrategy, Visitor, Interpreter, Template , Visitor, Interpreter, Template MethodMethod
Strategy (Behavioral Pattern)Strategy (Behavioral Pattern) Intent Intent – Define a family of algorithms, encapsulate – Define a family of algorithms, encapsulate
each one, and make them interchangeable. Strategy each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients lets the algorithm vary independently from clients that use it.that use it.
The Strategy pattern is often used as an alternative to inheritance, where we can end up spreading out the way we handle specific task over many class files.
Change the behavior at runtime (by using Composition Has - A relationship)
Example of Strategy pattern in a game :Example of Strategy pattern in a game :
Favor Composition over Inheritance HAS-A (Composition) can be better than IS-A (Inheritance) Allows changing behavior at run time The Character class will delegate its Weapon Behavior instead of
implementing these itselfCalling the setWeapon() Sample Code for getting new Sample Code for getting new
weaponweapon public abstract class Character {private WeaponBehaviour weapon;private WalkBehaviour walk;public void fight() {weapon.useWeapon(); // delegation of fight behaviour}public void setWeapon(WeaponBehaviour w){weapon = w;}...abstract void display();}
public class Mona extends Characterpublic class Mona extends Character
{{
public Mona()public Mona()
{{
weapon = new Sniper(); // The character Mona gets the Sniper weapon = new Sniper(); // The character Mona gets the Sniper weaponweapon
……
}}
public void display() {public void display() {
......
}}
}}
Uses of a Strategy Pattern –Uses of a Strategy Pattern –Strategy is used:Strategy is used: To configure a class with one of many behaviorsTo configure a class with one of many behaviors When we want to change the algorithm that we When we want to change the algorithm that we
use at runtimeuse at runtime
Consequences –Consequences – Families of related algorithmsFamilies of related algorithms An alternative to subclassingAn alternative to subclassing Strategies eliminate conditional statementsStrategies eliminate conditional statements Choice of different implementationsChoice of different implementations
DisadvantagesDisadvantages – – Strategy pattern can only be used when the Strategy pattern can only be used when the
variation in behavior is relevant to clientsvariation in behavior is relevant to clients
Patterns learned:Patterns learned: Prototype ~ Creational PatternPrototype ~ Creational Pattern Decorator ~ Structural PatternDecorator ~ Structural Pattern Strategy ~ Behavioral PatternStrategy ~ Behavioral Pattern
Advantages of Design PatternsAdvantages of Design Patterns They capture expertise and make it accessible to They capture expertise and make it accessible to
non-expertsnon-experts Reusing design knowledgeReusing design knowledge They form a vocabulary that helps developers They form a vocabulary that helps developers
communicate bettercommunicate better They help people understand a systems more They help people understand a systems more
quickly when it is documented with the patterns quickly when it is documented with the patterns it usesit uses
Focus is on developing flexible, maintainable Focus is on developing flexible, maintainable programsprograms
Using design patterns in the early life of software Using design patterns in the early life of software system design prevents later refactoringssystem design prevents later refactorings
Drawbacks of PatternsDrawbacks of Patterns
Patterns do not lead to direct code reuse
Individual Patterns are deceptively simple
Composition of different patterns can be very complex
Teams may suffer from pattern overload
Patterns are validated by experience and discussion rather than by automated testing
Integrating patterns into a software development process is a human intensive activity
CONCLUSIONCONCLUSION
THANK YOUTHANK YOU
??