0% found this document useful (0 votes)
31 views27 pages

UNIT-3-OOSE-part 1

Uploaded by

mk3532309
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views27 pages

UNIT-3-OOSE-part 1

Uploaded by

mk3532309
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

UNIT-IIIOBJECTORIENTEDANALYSIS DESIGN

SystemDesign,Architecture–DesignPrinciples-DesignPatterns–DynamicObject Modeling – Static Object


Modeling – Interface Specification – Object Constraint Language.

1. SystemDesign

 System design is the process of defining the architecture, components, modules, interfaces, and data for
a system to satisfy specified requirements.
 It involves translating user requirements into a detailed blueprint that guides the implementation phase.
 The goal is to create a well-organized and efficient structure that meets the intended purpose while
considering factors like scalability, maintainability, and performance.
Objectives of System Design

1. Practicality: We need a system that should be targeting the set of audiences(users) corresponding to which
they are designing.
2. Accuracy: Above system design should be designed in such a way it fulfills nearly all requirements around
which it is designed be it functional & non-functional requirements.
3. Completeness: System design should meet all user requirements
4. Efficient: The system design should be such that it should not overuse surpassing the cost of resources nor
under use as it will by now we know will result in low thorough put (output) and less response
time(latency).
5. Reliability: The system designed should be in proximity to a failure-free environment for a certain period of
time.
6. Optimization: Time and space are just likely what we do for code chunks for individual components to
work in a system.
7. Scalable(flexibility): System design should be adaptable with time as per different user needs of customers
which we know will keep on changing on time.
Elements of a System

 Architecture - This is the conceptual model that defines the structure, behavior and more views of a system.

We can use flowcharts to represent and illustrate the architecture.

 Modules - This are components that handle one specific task in a system. A combination of the modules

make up the system.

 Components - This provides a particular function or group of related functions. They are made up of

modules.

 Interfaces - This is the shared boundary across which the components of a the system exchange information

and relate.

 Data - This management of the information and data flow.

Advantages of System Design


 Reduces the design cost of a product.
 Speedy software development process
 Saves overall time in SDLC
 Increases efficiency and consistency of a programmer.
 Saves resources
System Architecture
Software architecture is a way in which we define how the components of a design are depictedthe
design and deployment of software.

Architecture serves as a blueprint for a system. It provides an abstraction to manage the system
complexity and establish a communication and coordination mechanism among components.

It defines a structured solution to meet all the technical and operational requirements, while optimizing
the common quality attributes like performance and security.
Different types of Software Architecture:
1. Layered Architecture :
As the name suggests, components(code) in this architecture are separated into layers of subtasks and they are
arranged one above another.
Each layer has unique tasks to do and all the layers are independent of one another. Since each layer is
independent, one can modify the code inside a layer without affecting others.
It is the most commonly used architecture for designing the majority of software. This layer is also known as
‘N-tier architecture’. Basically, this architecture has 4 layers.
1. Presentation layer (The user interface layer where we see and enter data into an application.)
2. Business layer (this layer is responsible for executing business logic as per the request.)
3. Application layer (this layer acts as a medium for communication between the ‘presentation layer’ and
‘data layer’.
4. Data layer (this layer has a database for managing data.)
Ideal for:
E-commerce web applications development like Amazon.
2. Client-Server Architecture:
The client-server pattern has two major entities. They are a server and multiple clients.
Here the server has resources(data, files or services) and a client requests the server for a particular resource.
Then the server processes the request and responds back accordingly.
Examples of software developed in this pattern:
 Email.
 WWW.
 File sharing apps.
 Banking, etc…
So this pattern is suitable for developing the kind of software listed in the examples.
3. Event-Driven Architecture :
Event-Driven Architecture is an agile approach in which services (operations) of the software are triggered by
events.
When a user takes action in the application built using the EDA approach, a state change happens and a
reaction is generated that is called an event.
Eg: A new user fills the signup form and clicks the signup button on Facebook and then a FB account is
created for him, which is an event.
Ideal for:
Building websites with JavaScript and e-commerce websites in general.
4. Microkernel Architecture :
Microkernel pattern has two major components. They are a core system and plug-in modules.
 The core system handles the fundamental and minimal operations of the application.
 The plug-in modules handle the extended functionalities (like extra features) and customized processing.
Microkernel pattern is ideal for Product-based applications and scheduling application and is mostly
preferred for app development.
5. MicroservicesArchitecture :
The collection of small services that are combined to form the actual application is the concept of
microservices pattern. Instead of building a bigger application, small programs are built for every service
(function) of an application independently. And those small programs are bundled together to be a full-
fledged application.
So adding new features and modifying existing microservices without affecting other microservices are no
longer a challenge when an application is built in a microservicesarchitecture.
Modules in the application of microservices patterns are loosely coupled. So they are easily understandable,
modifiable and scalable.
Example Netflix is one of the most popular examples of software built-in microservices architecture. This
architecture is most suitable for websites and web apps having small components.

Software Architecture- Data Flow Diagram


Software architecture can be depicted with a help of data flow diagram.
Data Flow Diagrams or DFDs is defined as a graphical representation of the flow of data through
information. DFD is designed to show how a system is divided into smaller portions and to highlight the flow
of data between these parts.
Here’s an example to demonstrate the Data Flow Diagram’s basic structure:

Data Flow Diagram’s basic structure

Components of a DFD:
Representation Action performed

Square Defines the source or destination of data

Identifies data flow and acts as a pipeline


Arrow
throughwhich information flows

Represents a process that transforms incoming


Circle/Bubble
data flow into outgoing data

It is a data store or data at rest/temporary


Open Rectangle
repository of data

Note: Sender and Receiver should be written in uppercase always. Rather it is good practrice to use
uppercaswe letter what so ever is placed in square box as per DFD conventions.
System Design Example: Airline Reservation System
Now since we have discussed about the basics of System Design so far, let us now understand System Design
through a basic example – Airline Reservation System.
To understand better about the components and design of Airline Reservation System, let us first review its
context-level flow diagram:
System Design Example: Airline Reservation System

Let us now understand the DFD of the Airline Reservation System:


 In the above flow diagram, Passenger, Travel Agent, Airline are the sources across which data is
migrating.
 Here data is transmitted from Passenger to book an Airline ticket as shown with the DFD arrow sign
where the travel request is placed.
 Now, this data is transmitted across two sources, as shown above, namely ‘Travel Agent‘ and ‘Airline‘
where if the seat is available Preferences and Air Flight request is placed to the source.
 Travel Agent and corresponding Ticketing are placed as requested.
 If no ticket is available, then a request for Passenger Reservation is placed to the source – Airline.

2. DesignPrinciples
Design principles establish practices that lend to develop software with considerations for maintaining and
extending as the project grows.

AdoptingDesign Principlespracticescanalsocontribute

 Well-designedsoftware iseasiertodebug,changeandextend
 Tomakebettersoftware.
 to helpthemproduce greatcode
 toavoid havingabad design.
 toavoidingcode smells
 refactoringcode
 AgileorAdaptivesoftwaredevelopment.
 writeflexibleandbettercodebystrivingforhighcohesionandlowcoupling

TOP10 Object oriented designprinciples

1. DRY(Don’trepeatyourself)-avoidsduplicationincode.

2. Encapsulatewhat changes-hidesimplementationdetailshelpsinmaintenance.

3. opencloseddesignprinciple-openfor extension,closedfor modification

4. SRP(singleresponsibilityPrinciple)-oneclassshoulddoonethinganddoitwell

5. DIP(Dependencyinversionprinciple)-don’taskletframeworkgivetoyou

6. Favorcompositionoverinheritance-codereusewithoutcostofinflexibility

7. LSP(liskovsubstitutionPrinciple)- subtypemustbesubstitutableforsupertype

8. ISP(Interface segretation Principle)- Avopid monolithic interface, reduce pain on cline side
9. Programmingfor interface-helpsinmaintenance,improvesflexibility

10. DelegationPrinciple- don’tdoallthingsbyyourself,delegateit.

1. DRY:

 Avoidduplicatecode--abstractoutthingsincommontoasinglelocation.
 Our first object-oriented design principle is DRY, as the name suggestsDRY (don't repeat
yourself) means don't writeduplicatecode, instead useAbstractionto abstract common things
in one place. If you have a block of code in more than two places, consider making it a
separate method, or ifyou use a hard-codedvalue more thanone time, make them as
 ‘Publicfinalconstant.’
 ThebenefitofthisObject-orienteddesignprincipleisinmaintenance.It'simportantnot to abuse it,
duplicationis not for code, but for functionality. It means if you used standardcodeto validate
OrderIDandSSN, it doesn’t meantheyarethesame, orthey will remain the same in the future.

 Byusingstandardcodefortwodifferentfunctionalityorthing,youtightlycouplethem forever, and


when your OrderId changes its format, your SSN validation code will break.

Example:Barcode()functionisreplicatedinbothstudentandlibraryclass.
Student
Library

Barcode() Barcode()

Example:Barcode()isfunctionisderivedandusedinbothstudentandLibraryclass.

Scan

Barcode()

Library
Student

2. EncapsulateWhat Changes

 Only one thing is constant in thesoftwarefield, and that is "Change," So encapsulate


thecodeyouexpectorsuspecttobechangedinthefuture.Thebenefitof thisOOP
DesignprincipleisthatIt'seasytotestandmaintainproperencapsulatedcode.

If you are coding in Java, then follow the principle ofmaking variables and
methodsprivatebydefaultandincreasingaccessstepbystep,likefromprivatetoprotectedand not
public.

3. OpenClosedDesignPrinciple
 Makecodewhichisopenforextending, butclosedformodifying.
 Open-closed principle – “Objects or entities should be open for extension but closed for
modification”

 Again, with future changes in mind, each class should be capable of being extended (open)
but its source code should not be changeable (closed).
 Classes, methods, or functions should be Open for extension (new functionality) and Closed
for modification. This design principle which prevents someone from changing already tried
and tested code.
 Ideally, ifyouareaddingnew functionalityonly, thenyour codeshouldbetested,and that's the goal
of the Open Closed Design principle.

Example: SupposeanOrderValidationclasshasamethod validate(Orderorder)thatis programmed to


validate an order based on a set of hard-coded rules. This design violates the OCP because if the rules
change,theOrderValidationclass has to be modified, tested, and compiled.

Abetterdesignwillbetoletthe OrderValidationclasscontainacollection ofValidationRule objects each


ofwhich has a validate(Order order) method (perhaps defined in aValidationinterface) to validate
anOrder using a specific rule, and the validate(Order order) methodof OrderValidation class
cansimplyiteratethrough those ValidationRule
objects to validate the order. The new design will satisfy the OCP,
becauseiftheruleschange,wecanjustcreateanew ValidationRule objectandadditto an OrderValidation
instance at run time (rather than to the class definition itself).
This is can also be achieved by usingsubclasses of a base class AbstractValidationRule that has an
override-able function validate(Order order). Subclasses can implement the method differently
without changing the base class functionality.

4. SingleResponsibilityPrinciple(SRP)
 Single responsibility principle – “A class should have one and only one reason to change,
meaning that a class should have only one job”

 Theideaisthateachindividualclassonlyhasresponsibilityforonepartofthesoftware or
digitalproduct’s function; i.e. each class does just one thing, keeping the design as simple as
possible and therefore future changes and updates are easier and less disruptive.
 Classesshouldnothavemorethanonefocusofresponsibility.

 SRP, there should not be more thanone reason fora classto change, ora class should always
handle single functionality.

 IfyouputmorethanonefunctionalityinoneClassinJava,it introducescouplingbetween two


functionality, and even if you change one feature, there is a chance you broke coupled
functionality,which requires another round of testing to avoid any surprise on the production
environment.
 TheSRPrequiresthataclassshouldhaveonlyasingle responsibility.

Example: If a classSalesOrder keeps information about a sales order, and in addition has a
methodsaveOrder() that saves theSaleOrder in a database and a method exportXML()that exportsthe
SalesOrder in XML format, this design will violate the SRP because there will be different types of
users ofthis class and different reasons for making changes to this class. A change made for one type
of user, say change the type of database, may require the re-test, recompilation, and re-linking of the
class for the other type of users.

A better design will be to have the SalesOrder class only keeps the information about a sales
order,andhavedifferent classesto saveorderandtoexportorder,respectively.Suchadesign will confirm to
SRP.

5. DependencyInjectionorInversionprinciple
 Don'tdependonconcreteclasses,dependonabstractions

 Dependency inversion principle – “Entities must depend on abstractions, not on concretions.It


statesthat thehigh-levelmodule must notdependonthe low-levelmodule, but they should depend on
abstractions”
 The idea here is to decouple the software’s modules, avoiding unnecessarydependencies,
resultingincodethatismoreflexibleandreusable. Don't askfordependency;it
willbeprovidedtoyoubytheframework.Thishasbeenvery wellimplemented inthe Spring
framework,thebeautyofthis designprinciple isthat any class which is injected bythe DIframework
is easytotest withthe mockobject and more comfortable to maintain because object creation code
is centralized in the framework and the client code is not littered with that.

 The DIP requires that high level modules should not depend on low level modules, both
shoulddependonabstraction.Also,abstractionshouldnotdependondetails,detailsshould depend on
abstractions.

Example: MakingaclassButtonassociatetoanotherclass Lamp(becauseaLamphas a Button) is a


violation of DIP. A better design will be associate an AbstractButton with an AbstractButtonClient,
and define Button as a subclass of the AbstractButton and a Lamp a subclass of the
AbstractButtonClient.

Example: MakinganEBookReader classto use PDFBook class isa violationofDIPbecause it requires


to change the EBookReader class to readother types ofe-books. Abetter design is to let EBookReader
use an interface EBookand let PDFBook and other types of e-book classesimplement
EBook.Nowaddingorchanginge-bookclasseswillnotrequireanychange to EBookReader class.

6. FavorComposition overInheritance
 Always favor composition over inheritance,if possible. Some of you may argue
this,butIfoundthatCompositionisalotmoreflexiblethan Inheritance.

Compositionallowschangingthebehaviorofaclassatrun-timebysettingproperty duringrun-
time,andbyusingInterfacestocomposeaclass,weusepolymorphism, which provides
flexibility to replace with better implementation at any time.

7. LiskovSubstitutionPrinciple(LSP)

 Subclassobjectsmust alwaysbesubstitutableforsuperclassobjects
 Liskov substitution principle – “Let q(x) be a property provable about objects of x of
typeT.Thenq(y) shouldbeprovableforobjectsyoftypeS whereSisasubtypeofT”

 Or, in other words, each derived class is substitutable for its parent class – similar to the open-
closed principle, it ensures that extending derived classes cannot fundamentally change the
behavior of the product.

 According tothe Liskov Substitution Principle, Subtypes must be substitutable for supertype,
i.e. methods or functions which use superclass type must be able to work with the
object of subclass without any issue". LSP is
closely related to the Single responsibility principle and Interface Segregation Principle.
If a class has more functionality, then the subclass might not support some of the functionality
and does violate LSP.
 TheLSPrequiresthatobjectsinaprogramshouldbereplaceablewithinstancesoftheir subclasses
without altering the correctness of that program.
 The users must be able to use objects of subclasses via references to base classes without
noticinganydifference. Whenusinganobject throughitsbaseclass interface,
theobjectofasubclassmustnotexpecttheusertoobeypreconditionsthatarestronger than those
required by the base class.
Example:

Supposea Rectangle classhastwoinstancevariables height and width,anda


methodsetSize(inta,intb),whichset height toaandwidthtob.SupposeSquareisasubclass ofRectangleand it
overrides the inherited method by setting bothheight andwidthtoa. This
designwillviolateLSP.Toseethis,consideraclientusesareferencevariableof typeRectangleto call the
setSize() method to assign different values ofaandb, and then
immediatelyverifyifthesizesweresetcorrectlyortheareaiscorrectlycomputed.Theresults will be different
if the variable references to a Rectangle object than to a Squareobject.

It turns out that in OO programming, a Squareis not aRectangleat all because it behaves differently
from a Rectangle.

8. InterfaceSegregationPrinciple(ISP)
 Clients should not be forced to depend on methods (inherit from or implement) they don't use
 Interfacesegregation–“Aclient shouldneverbeforcedtoimplement an interfacethat it doesn’t
use, or clients shouldn’t be forced to depend on methods theydo not use”
 Thisencouragesmultiple,client-specificinterfacesratherthanattemptingtoextendthe use of an
existing interface.
 TheInterfaceSegregationPrinciple
statesthataclientshouldnotimplementaninterfaceifitdoesn'tusethat.Thishappensmostlywhenonei
nterfacecontainsmore than one functionality, and the client only needs one functionality and
no other. Interface design is a tricky job because once you release your interface, you can not
change it without breaking all implementation.
 The ISP requires that clients should not be forcedto depend on interfaces that theydo not use.

Example: SupposeaVehicle interface shown in the figure is designed for clients to use.

ThisviolatesISPbecauseclientsareforcedtodependonmethodstheydonot use: HighWaydoesnotuse


stopRadio() or ejectCD(),and ParkingLot doesnot need accelerate() or ejectCD().
figure

Another benefit of this design principle in Java is, the interface has the disadvantage of
implementingallmethodsbeforeanyclasscanuseit,sohavingsinglefunctionalitymeansless method to
implement

9. ProgrammingforInterfacenotimplementation
Alwaysprogram for the interface and not for application; this will lead to flexible code that
canworkwithanynewimplementationoftheinterface.

So use interface type on variables, return types of method, or argument type of methods in Java.

10. Delegationprinciples
Don't doallstuffbyyourself,delegate ittotherespectiveclass.Thekeybenefit ofthisdesign principle is no
duplication of code and pretty easy to modify behavior. Event delegation is another example of this
principle, where an event is delegated to handlers for handling.

Delegationissimplypassing adutyofftosomeone/something else.

 Delegationcan beanalternativetoinheritance.
 Delegation means that you use an object of another class as an instance variable, and forward
messages to the instance.
 It is better than inheritance for many cases because it makes you to think about each
messageyouforward,becausetheinstanceisofaknownclass,ratherthananewclass,and because it
doesn’t force you to accept allthe methods ofthe super class: you can
provideonlythemethodsthatreallymakesense.
 Delegation can be viewed as a relationship between objects where one object forwards certain
method calls to another object, called its delegate.
 The primary advantage of delegation is run-time flexibility – the delegate can easily be changed at
run-time. But unlike inheritance,delegation is not directly supported by most popular object-
oriented languages, and it doesn’t facilitate dynamic polymorphism.

// Javaprogramtoillustrate
//delegation
classExamCell{
//the"delegate"
voidprintresult()
{
System.out.println("SemesterResultspublishedtomorrow---TheDelegate");
}
}

classDept{
//the"delegator"
ExamCellp=newExamCell();

//createthedelegate
voidprintresult()
{
p.printresult();//delegation
}
}

publicclassTester{

//TotheoutsideworlditlookslikeDeptactuallyprintstheresultsthanexamcell
publicstaticvoidmain(String[]args)
{
DeptI=newDept();
I.printresult();
}
}

Design Patterns
The design which is used for an older problem is also used to design the solution to a new problem.
Such a common design is known as a pattern of design. The design pattern is one which is used to
design a problem which was extracted from older problems.

Uses:

Greater help to beginners.

Code structure easier to understand.


Guide for individual solution.

No need to invert new designs.

GRASPDesignprinciples:

GRASP tends to take a responsibility focus, like who creates this object,who is in charge of how these
objects talk to each other,who takes care of passing all messages received from a user interface?, etc.

 GRASP=objectorienteddesignwithresponsibilities
 Stands for General Responsibility Assignment Software Pattern.
 guidesinassigningresponsibilitiestocollaboratingobjects.

Types of GRASP pattern


1. Creator
2. InformationExpert
3. Low Coupling
4. Controller
5. HighCohesion
6. Indirection
7. Polymorphism
8. Protected Variations
9. PureFabrication

1. Creator
Whoshouldberesponsibleforcreatinganewinstanceofsomeclass?
AssignclassBtheresponsibilitytocreateaninstanceofclassAifoneoftheseistrue(themore the better):

B“contains”orcompositelyaggregatesA. B

records A.
Bcloselyuses A.
BhastheinitializingdataforAthat willbepassedtoAwhenit iscreated.ThusBisanExpert with respect to
creating A.

ExampleforCreator
● ConsiderVideoStoreandVideo inthatstore.
● VideoStore has an aggregation association with Video. I.e, VideoStore is the container and the
Video is the contained object.
● So,wecaninstantiatevideoobjectinVideoStoreclass

Example for creator

2. InformationExpert
Whatisageneralprincipleofassigningresponsibilitiestoobjects?
Assignaresponsibilitytotheinformationexpert—theclassthathastheinformationnecessary to fulfill the
responsibility.
 Givenanobject o,whichresponsibilitiescan beassigned too?
 Expertprinciplesays–assignthoseresponsibilitiestooforwhichohastheinformation to fulfill that
responsibility.
 Theyhavealltheinformationneededtoperformoperations,orinsomecasesthey collaborate with
others to fulfill their responsibilities.
ExampleforExpert
● Assumeweneed to getallthevideosofaVideoStore.
● SinceVideoStoreknowsaboutallthevideos,wecanassignthisresponsibilityofgiving all the videos
can be assigned to VideoStore class.
● VideoStoreistheinformationexpert.
ExampleforExpert:

3. LowCoupling
Howtosupportlowdependency,lowchangeimpact,andincreasedreuse?
Assignaresponsibilitysothatcouplingremainslow.Usethisprincipletoevaluatealternatives. How strongly
the objects are connected to each other?
 Coupling–objectdependingonotherobject.
 When depended up on element changes,it affects the dependantal so.
 LowCoupling –Howcanwereducethe impact ofchange independeduponelements on dependant
elements.
 Preferlowcoupling–assignresponsibilitiessothat couplingremainlow.
 Minimizesthedependencyhencemakingsystemmaintainable,efficientandcode reusable

Two elements are coupled,if – One elementhasaggregation/composition association with another


element. – One element implements/extends other element.

Exampleforpoorcoupling

here class Rent knows about both VideoStore and Video objects. Rent is depending on both the
classes.
Exampleforlowcoupling
● VideoStoreandVideoclassarecoupled,andRentiscoupledwithVideoStore.Thus providing low
coupling.

4. Controller
WhatfirstobjectbeyondtheUIlayerreceivesandcoordinates(“controls”)asystemoperation? Assign the
responsibilityto a class representing one ofthe following choices:
 Represents the overall “system”,a“root object”,adevicethatthesoftwareisrunning within, or a
major subsystem — these are all variations ofa facade controller.
 Representsausecasescenariowithinwhichthesystemoperationoccurs,oftennamed
<UseCaseName>[Handler|Coordinator|Session](usecaseorsessioncontroller).
 Deals with how to delegatetherequestfromtheUI layerobjectstodomainlayer objects.
● whenarequest comes fromUI layerobject, Controllerpatternhelpsus indeterminingwhat is that first
object that receive the message from the UI layer objects.
● This object is called controller object whichreceives request fromUI layer object and then
controls/coordinates with other object of the domain layer to fulfill the request.
● Itdelegatestheworktootherclassand coordinatestheoverallactivity

We can makea n object as Controller, if–Objectrepresentstheoverallsystem(facade controller)–Object


represent ausecase, handling a sequence of operations(session controller).

Example for Controller

Benefits–
 Can reuse this controller class.–
 Canuse tomaintainthe stateofthe use case.
 Cancontrolthesequenceoftheactivities

5. High Cohesion
Howtokeepobjectsfocused,understandable,andmanagable,andasasideeffect,supportLow Coupling?
Assignaresponsibilitysothatcohesionremainshigh.Usethistoevaluatealternatives.
Howaretheoperationsofanyelement arefunctionallyrelated?
● Relatedresponsibilitiesintoonemanageableunit.●Preferhighcohesion
● Clearlydefinesthepurposeofthe element

Benefits–
 Easilyunderstandableandmaintainable.
 Codereuse
 Lowcoupling

Example for low cohesion

ExampleforHigh Cohesion
6. Polymorphism
Howhandlealternativesbasedontype?Howtocreatepluggablesoftwarecomponents?
Whenrelatedalternativesorbehaviorsvarybytype(class),assignresponsibilityforthe behavior — using
polymorphic operations —to thetypes for which the behavior varies.

Howtohandlerelatedbutvaryingelementsbasedonelement type?
● Polymorphismguidesus indeciding whichobject isresponsible for handling those varying elements.
Benefits:
Handling new variations will be come easy

ExampleforPolymorphism
thegetArea() varies by the type of shape, so we assign that responsibilityto the subclasses. By
sendingmessage to the Shape object, a call will be made to the corresponding sub classobject – Circle
or Triangle

7. Indirection
Wheretoassignaresponsibility, to avoiddirect couplingbetweentwo(ormore)things?How to de-couple
objects sothat low coupling is supported andreusepotentialremains higher?
Assign the responsibility toan intermediate object to mediate between other components or services so
that they are not directly coupled.
How can we avoid a direct coupling between two or more elements.
● Indirection introduces an intermediate unit to communicate betweenthe other units, so that the other
units are not directly coupled.
Benefits:lowcoupling
Example:Adapter,Facade,Obserever
ExampleforIndirection
Herepolymorphismillustratesindirection
● ClassEmployeeprovidesalevelofindirectiontootherunitsofthesystem.

8. PureFabrication
Whatobjectshouldhavetheresponsibility,whenyoudonotwanttoviolateHighCohesionand Low Coupling,
orother goals, but solutions offered byExpert are not appropriate?
Assignahighlycohesivesetofresponsibilitiestoanartificialorconvenienceclassthatdoesnot representa
problem domain concept—something made up, to support high cohesion, low coupling, and reuse.

Fabricatedclass/artificialclass–assignsetofrelatedresponsibilitiesthatdoesn'trepresentany domain object.


● Providesahighlycohesivesetofactivities.
● Behavioraldecomposed–implementssomealgorithm.
● Examples:
Adapter,Strategy
Benefits:
Highcohesion,lowcouplingandcanreusethisclass.
Example
SupposeweShapeclass,ifwemuststoretheshapedatainadatabase.
● If we put this responsibility in Shape class, there will be many database related operations thus
making Shape incohesive.
● So,createafabricatedclassDBStorewhichisresponsibletoperformalldatabaseoperations
.●SimilarlylogInterfacewhichisresponsible forlogging informationisalso agoodexample for Pure
Fabrication.

9. ProtectedVariations
How to design objects, subsystems, and systems so that the variations or instability in theseelements
does not have an undesirable impact onother elements?
Identify points of predicted variation or instability; assign responsibilitiestocreatea stable interface
around them.
Howtoavoidimpactofvariationsofsome elementsonthe otherelements.
● Itprovidesawelldefinedinterfacesothatthetherewillbenoaffectonother units.
● Providesflexibilityandprotectionfromvariations.
● Providesmorestructured design.
Example:polymorphism,dataencapsulation,interfaces

GOFDesign Patterns
 GOF (Gang of Four) patterns are and how they help solve common problems encountered in
object-oriented design.
 Adesignpatternisageneralreusablesolutiontoacommonlyoccurringproblemwithin a given
context. What does that mean?
 Programmersoftenencounterthesameproblemrepeatedly.Ratherthanhaveeveryone
comeupwiththeirownsolutiontocommonprogrammingissues,weuseabestpractice type solution
that has been documented and proven to work.
 Thewordgeneralis important.Wecannotjustcopyandpasteadesignpatternintoour code. A design
pattern represents an idea, and we should write an implementation for that pattern and
implement that in our code.

Gang ofFourDesignPatterns

There are 23 design patterns described by Erich Gamma, Richard Helm, Ralph Johnson, and John
Vlissides known GOF (Gang of Four) design patterns.

GoF Design Pattern Types

GoF Design Patterns are divided into three categories:

1. Creational: The design patterns that deal with the creation of an object.
2. Structural: The design patterns in this category deals with the class structure such as Inheritance and
Composition.
3. Behavioral: This type of design patterns provide solution for the better interaction between objects, how to
provide lose coupling, and flexibility to extend easily in future.
Creational Design Patterns
There are 5 design patterns in the creational design patterns category.

Pattern Name Description

The singleton pattern restricts the initialization of a class to ensure that only one instance of
Singleton
the class can be created.

The factory pattern takes out the responsibility of instantiating a object from the class to a
Factory
Factory class.

Abstract Factory Allows us to create a Factory for factory classes.

Builder Creating an object step by step and a method to finally get the object instance.

Creating a new object instance from another similar instance and then modify according to
Prototype
our requirements.

Structural Design Patterns

There are 7 structural design patterns defined in the Gangs of Four design patterns .

Pattern
Description
Name

Adapter Provides an interface between two unrelated entities so that they can work together.

Used when we have to implement a part-whole hierarchy. For example, a diagram made of other
Composite
pieces such as circle, square, triangle, etc.

Proxy Provide a surrogate or placeholder for another object to control access to it.

Flyweight Caching and reusing object instances, used with immutable objects. For example, string pool.

Facade Creating a wrapper interfaces on top of existing interfaces to help client applications.
Pattern
Description
Name

The bridge design pattern is used to decouple the interfaces from implementation and hiding the
Bridge
implementation details from the client program.

Decorator The decorator design pattern is used to modify the functionality of an object at runtime.

Behavioral Design Patterns

There are 11 behavioral design patterns defined in the GoF design patterns.

Pattern Name Description

used to create a template method stub and defer some of the steps of implementation to
Template Method
the subclasses.

used to provide a centralized communication medium between different objects in a


Mediator
system.

Chain of used to achieve loose coupling in software design where a request from the client is
Responsibility passed to a chain of objects to process them.

useful when you are interested in the state of an object and want to get notified whenever
Observer
there is any change.

Strategy pattern is used when we have multiple algorithm for a specific task and client
Strategy
decides the actual implementation to be used at runtime.

Command Command Pattern is used to implement lose coupling in a request-response model.

State design pattern is used when an Object change it’s behavior based on it’s internal
State
state.
Pattern Name Description

Visitor pattern is used when we have to perform an operation on a group of similar kind
Visitor
of Objects.

defines a grammatical representation for a language and provides an interpreter to deal


Interpreter
with this grammar.

Iterator used to provide a standard way to traverse through a group of Objects.

The memento design pattern is used when we want to save the state of an object so that
Memento
we can restore later on.

Conclusion

Gangs of Four design patterns lay the foundation of core design patterns in programming. There are many other
design patterns built on top of these patterns for specific requirements.

CreationalPatterns
The first type of design pattern is the creationalpattern. Creational patterns provide ways to instantiate
single objects or groups of related objects. There are five such patterns:

Creationalpatternsoftenused inplaceofdirect instantiationwithconstructors.Theymakethe


creation process more adaptable and dynamic. In particular, they can provide a great deal of
flexibility about which objects are created, how those objects are created, and how they are
initialized.

Design Purpose
Pattern

Name

Builder designpatternis analternative wayto construct complexobjects and


Builder should be used only when we want to build different types of immutable
objects using same object building process.
Prototype design pattern is used in scenarios where application needs to create
Prototype a large number of instances of a class, which have almost same state or differ
very little.

Factory design pattern is most suitable when complex object creation steps are
Factory involved. To ensure that these steps are centralized and not exposed to
composing classes.

Abstractfactory Abstractfactorypatternisusedwheneverweneedanotherlevelof abstraction over a


group of factories created using factory pattern.

Singleton enables an application to have one and only one instance of a class per
Singleton
JVM.

StructuralPatterns
Thesecondtypeofdesignpatternisthe structuralpattern.Structuralpatternsprovideamanner to define
relationships between classes or objects.
Structuraldesignpatternsshowushowtogluedifferentpiecesofasystemtogetherinaflexible and extensible
fashion. These patterns help us guarantee that when one of the parts changes, the entire application
structure does not need to change.

Design
Purpose
Pattern
Name
An adapter convert the interface of a class into another interface clients
Adapterter expect. It lets classes work together that couldn’t otherwise because of
incompatible interfaces.

Bridgedesignpatternisusedtodecoupleaclassintotwoparts –abstractionand
it’s implementation– so that both can evolve in future without affecting
Bridge
each other. It increases the loose coupling between class abstraction and
it’s implementation.

Composite design pattern helps to compose the objects into tree


Composite structurestorepresent whole-part hierarchies. Composite letsclients treat
individual objects and compositions of objects uniformly.

Decorator design pattern is used to add additional features or


Decorator behaviorstoaparticularinstanceofaclass,whilenotmodifyingthe other
instances of same class.
Facade design pattern provide a unified interface to a set of interfaces in
Facade a subsystem. Facade defines a higher-level interface that makes the
subsystem easier to use.

Flyweight design pattern enables use sharing of objects to support large


numbers of fine-grained objects efficiently. A flyweight is a shared
Flyweight
object that canbe used in multiple contextssimultaneously. The flyweight
acts as an independent object in each context.

In proxy design pattern, a proxy object provide a surrogate or


placeholder for another object to control access to it. Proxy is heavily
Proxy
used to implement lazy loading related usecases where we do not want to
create full object until it is actually needed.

BehaviouralPatterns
Thefinaltypeofdesignpatternisthebehaviouralpattern.Behaviouralpatternsdefinemanners of
communication between classes and objects.
Behavioralpatternsabstractanactionwewanttotakeontheobjectorclassthattakestheaction.
Bychangingtheobject or class, wecanchangethealgorithmused,theobjectsaffected,orthe behavior, while
stillretaining the same basic interface for client classes.

Design Pattern
Name Purpose

Chain of responsibility design pattern gives more than one object an


Chain of opportunitytohandlearequestbylinkingreceivingobjectstogetherin form of a
responsibility chain.

Command design pattern is useful to abstract the business logic into discrete
actions which we call commands. These command objects help in loose
Command coupling betweentwo classeswhere one class(invoker) shall call a method
on other class (receiver) to perform a business operation.

Interpreter pattern specifies how to evaluate sentences in a language,


Interpreter programatically.Ithelpsinbuildingagrammarforasimplelanguage, so that
sentences in the language can be interpreted.
Iterator patternprovides a wayto access the elements ofanaggregate object
Iterator
sequentially without exposing its underlying representation.

Mediator pattern defines an object that encapsulates how a set of


objectsinteract.Mediatorpromotesloosecouplingbykeepingobjects from
Mediator
referring to each other explicitly, and it lets us vary their interaction
independently.

Mementopatternisusedtorestorestateofanobjecttoapreviousstate. It is also
Memento
known as snapshot pattern.

Observer pattern defines a one-to-many dependency between objects so that


when one object changes state, all its dependents are notified and updated
Observer
automatically. It is also referred to as the publish- subscribe pattern.

In state pattern allows an object to alter its behavior when its internal
State statechanges.Theobjectwillappeartochangeitsclass.Thereshallbe a separate
concrete class per possible state of an object.

Strategypatternisusedwherewechooseaspecific implementationof
Strategy algorithmor task in run time – out of multiple other implementations for
same task.

Template method pattern defines the sequential steps to execute a multi-step


Template method algorithm and optionally can provide a default implementation as well
(based on requirements).

Visitor patternisused whenwe want a hierarchyofobjectsto modify their


Visitor
behavior but without modifying their source code.

A.Creational Design Patterns

1.Factory Method Design Pattern


Factory Method Design Pattern is a creational design pattern among the Gang Of Four(GOF) Design Patterns.
Being a creational design pattern, the factory method design pattern deals with the creation of a family of
objects.
Factory method design pattern creates objects in such a way that it lets the sub-classes decide how to implement
the object creation logic.

In the factory pattern, there is a base factory interface/base class which defines a common method for creating
objects of subclasses. The actual logic for creation of different type of objects is present in the
implementations/subclasses, which determine how to implement the creation logic by overriding the pre-defined
instance creation method. Lets have a look at the class diagram of a factory method design pattern to understand
it better.
UML Class Diagram for Factory Method Design Pattern
Explanation of the code

 BaseProduct is the base interfaces for all products.


 ConcreteProduct implements BaseProduct. There are usually multiple ConcreteProduct implementations for
a BaseProduct when a factory design pattern is chosen for object creation.
 FactoryInterface defines the basic behavior of the factory which in this case is defined by the
method getInstance().
 ConcreteFactory implements FactoryInterface and provides implementation for the getInstance() method.
There can be mutiple ConcreteFactory sub-classes.
 The ConcreteFactory’s getInstance() method creates an object of one of the ConcreteProduct classes. It
however sends back an object of type BaseProduct.
 The actual object created is as per the client invocation context. I.e. if the client asks ConcreteFactory to
give ConcreteProduct of say type-X, getInstance() sends back an object of that type. If the client asks for type-
Y, then it gets back an object of that type and so on.
 The object creation method getInstance() of ConcreteFactory is thus standardized and it creates objects
of ConcreteProduct set of classes while returning the object in a BaseProduct reference. This is the Factory
Method Design Pattern.

2.Prototype Design Pattern


prototype Design Pattern is a creational design pattern among the Gang Of Four(GOF) Design Patterns. Being a
creational design pattern, the Prototype pattern deals with the design of how the object creation is
managed. What is Prototype Design Pattern In a Prototype Design Pattern implementation the type of object
to be created is specified using a prototypical instance. New objects are created by copying(or cloning) this
prototype. In simpler terms, in Prototype Pattern we keep an object of the type we want to create and any new
object is created by simply cloning this existing object. Scenarios in which Prototype Design Pattern can be
used

1. Exact class to be instantiated is specified dynamically : When the class of which instance is to be created is
specified at runtime, then Prototype pattern can be used.
2. Object creation using 'new' keyword is costlier : When the inherent cost of object creation using 'new'
keyword is more than simply cloning an existing standard object.
3. When Abstract Factory-like class hierarchy is not required : To avoid maintaining an abstract factory like
class hierarchy of multiple factories.
4. Object States can be pre-defined : If the objects to be created can only have one of a finite number of states,
then keeping prototypes of these objects and cloning them when needed is more convenient

Class Diagram for Prototype Design Pattern


Explanation of Prototype Design Pattern's Class Diagram

 Prototype is the base interface with a single method clone().


 Every concrete class which can be cloned must extend Prototype and override the clone() method.
 Every child of Prototype implements its own cloning logic in the overriden clone() method.
 Client invokes the clone method of the concrete child of Prototype and gets a cloned object back.

B.Structural Design Patterns

1.Adapter Design Pattern

Adapter class makes classes with incompatible interfaces work together. Adapter Design Pattern is
a structural design pattern among the Gang Of Four(GOF) Design Patterns. I.e. the adapter pattern deals with
how the classes are composed to form larger structures.
What is Adapter Design Pattern When the target class has an interface which is different from what the client
class expects, then adapter pattern solves this problem by converting the interface of the target into the client
expected one. As a result classes which otherwise would not have been able to communicate with each other can
now communicate with ease. Variants of Adapter Design Pattern Adapter design pattern has 2 variants -

1. Class Adapters : Class Adapter works by subclassing both the Target and the Adaptee. Adapter overrides the
Target interface methods such that every client call made on the overridden target interface is redirected to the
Adaptee's inherited method which does the actual operation. Class Adapter's class diagram is as shown below -
 Adapter inherits both from Target and Adaptee.
 The client invokes requiredMethod() on an instance of Adapter which is also an instance of Target by
virtue of being its subclass.
 Adapter overrides the requiredMethod() of Target and in its implementation internally
calls Adaptee’s targetMethod().
 Thus, Client is able to use targetMethod() functionality from Adaptee through the Adapter without
change of the interface which still remains Target for the client.
2. Object Adapters : Object Adapter works by composing the Adaptee and extending the Target. Adapter
overrides the Target interface methods such that every client call made to the overridden target interface's
method is redirected to the composed Adaptee object's method which does that operation. Let's have a look at
the class diagram for Object Adapters -

Explanation of Class Diagram

 Adapter extends Target.


 Adapter also keeps an instance of Adaptee as a class variable.
 When Client calls -
 The Client invokes requiredMethod() on an instance of Adapter which is also an instance of Target by
virtue of being its subclass.
 Adapter overrides the requiredMethod() of Target and in its implementation internally calls its class
variable adaptee's targetMethod().
 Thus, Client is able to use targetMethod() functionality from Adaptee through the Adapter without
change of the interface which still remains Target for the client.

2.Facade Design Pattern

Facade Design Pattern is a structural design pattern among the Gang Of Four(GOF) Design Patterns. Being a
structural design pattern, the facade pattern basically deals with how the classes are composed together to get the
desired outcome from a system. What is Facade Design Pattern The basic design problem which the facade
pattern solves is to simplify access to a set of interfaces in a subsystem. Facade solves this problem by
providing a higher-level interface one level above all the sub-level interfaces. This higher-level interface then
deals with the details and intricacies of the subsystem interface and at the same time provides a simplified
interfaces to the clients of the subsystem.

Facade pattern improves decoupling between the clients and subsystems as the higher-level interface can
absorb any changes which might happen in the lower subsystems interfaces and provide a consistent interface to
the clients. This also has a direct benefit of system portability as the clients only design and code for the higher-
level interface defined by the Facade. Porting of the subsystems then becomes easy as all the complexity of
porting is hidden from the clients by the Facade layer.
Layered subsystems can have a facade for each layer. Thus communication between layers of the subsystem
is much simplified as it happens through the subsystem facades rather than directly deal with the complexities of
the subsystem's individual classes.

Explanation of Class Diagram

 The classes to the extreme right belong the Sub-System(depicted by the UML notation of ::).
 There are N subsystem classes-Class1,Class2...ClassN.
 Facade layer, or Facade class as per this class diagram, invokes the sub-system classes as per the client request
received by it on one of its simplifiedMethods().
 SimplifiedMethods() in turn invoke multiple subsystem classes based on the business
logic. SimplifiedMethods() may talk to multiple sub-system classes as per the business logic and in the end
come up with the simplified/aggregated response which can be sent back to the client.
 The Client class creates, or holds, an instance of the Facade and invokes the specific simplifiedMethod() as
per his needs. He just invokes the simplifiedMethod() and in return gets the simplified/aggregate response.
Thus, the Client is shielded from the underlying complexities of the sub-system layer by the Facade.

C.Behavioral Design Patterns

1.Observer Design Pattern

Observer Design Pattern is a behavioral design pattern among the Gang Of Four(GOF) Design Patterns. Being a
behavioral design pattern, the Observer pattern deals with how objects of the designed system interact with each
other. What is Observer Design Pattern Observer Design Pattern is used when there are multiple subscribers
observing updates from a publisher. The publisher, known as Subject, publishes its change of state to its
subscribers. Subscribers, known as Observers, receive these changes and update themselves
accordingly. Scenarios in which Observer Design Pattern can be used

1. Change of an object requires changes to multiple others : When there is an observed object(a.k.a the
Subject), then there should be a mechanism to notify its changes to multiple of its observer components which
have evinced interest in listening to these changes without the exact quantity of observers being known at
design time.
2. Notification capability needed without tight rules regarding how this notification is used : When the
different Observers of notifications from a Subject have there own presentation and\or business logic
implementation, but still need to have the capability of getting the latest updates from Subject. I.e. Observers
are loosely coupled with the Subject

Class Diagram for Observer Design Pattern


Explanation of Observer Design Pattern's Class Diagram

 Subject is the one being observed. It has attach() & detach() methods to add or remove observers
respectively. It uses notify() method to publish its changes to observers\subscribers.
 Observer objects register\attach themselves to the Subject they want to listen to for updates.
 ConcreteObserver instances are actual Observer objects which treat the notifications they receive from
the Subject in their own individual ways.
 ConcreteSubject is the actual Subject object whose state change is notified to multiple observers.

2.Strategy Design Pattern

Strategy Design Pattern is a behavioral design pattern among the Gang Of Four(GOF) Design Patterns. I.e. the
strategy design pattern deals with how the classes interact with each other. What is Strategy Design
Pattern Strategy Pattern is used when there is a family of interchangeable algorithms of which one algorithm is
to be used depending on the program execution context. Strategy Pattern achieves this by clearly defining the
family of algorithms, encapsulating each one and finally making them interchangeable. Each of the algorithms
in the family can vary independently from the clients that use it. Interchangeability is achieved by making a
parent interface/base strategy class and keeping individual algorithms as children of this base class. The client
class holds a reference to the base strategy and at runtime receives the correct algorithm child instance
depending on the execution context.

Lets have a look at the class diagram of the strategy pattern -


Strategy Design Pattern Class Diagram

Explanation of Class Diagram


 BaseStrategy class is an abstract class which represents the algorithm.
 executeAlgorithm() is the abstract method in BaseStrategy which is responsible for executing the algorithm,
but is puposefully kept abstract so that each of the child strategies/algorithms can implement this method with
their own logic.
 ConcreteStrategy1 & ConcreteStrategy2 are two subclasses of BaseStrategy. These 2 are infact two
different variants of the algorithm represented by the BaseStrategy.
 ConcreteStrategy1 & ConcreteStrategy2 override executeAlgorithm() method from BaseStrategy to
provide the implementation of the algorithm variant as per their own needs.
 Lastly, the Context class invokes this algorithm. Based on the need of the execution context specific variant of
the BaseStrategy - either of ConcreteStrategy1 or ConcreteStrategy2 is assigned to
the baseStrategyInstance variable of Context.
 Context always invokes baseStrategyInstance variable's executeAlgorithm() method, but the actual
algorithm which is executed is based on which instance of ConcreteStrategy is held
by baseStrategyInstance.

Note - I have shown 2 concrete instances named ConcreteStrategy1 & ConcreteStrategy2 just for explanation.
There can be more than 2 concrete instances as per needs of the design. Strategy Design

You might also like