UNIT-3-OOSE-part 1
UNIT-3-OOSE-part 1
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.
Modules - This are components that handle one specific task in a system. A combination of the modules
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.
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.
Components of a DFD:
Representation Action performed
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
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
1. DRY(Don’trepeatyourself)-avoidsduplicationincode.
2. Encapsulatewhat changes-hidesimplementationdetailshelpsinmaintenance.
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
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.
Example:Barcode()functionisreplicatedinbothstudentandlibraryclass.
Student
Library
Barcode() Barcode()
Example:Barcode()isfunctionisderivedandusedinbothstudentandLibraryclass.
Scan
Barcode()
Library
Student
2. EncapsulateWhat Changes
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.
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.
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
The DIP requires that high level modules should not depend on low level modules, both
shoulddependonabstraction.Also,abstractionshouldnotdependondetails,detailsshould depend on
abstractions.
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:
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.
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.
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:
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.
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
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
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
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
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.
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.
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.
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.
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.
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.
There are 11 behavioral design patterns defined in the GoF design patterns.
used to create a template method stub and defer some of the steps of implementation to
Template Method
the subclasses.
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.
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.
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:
Design Purpose
Pattern
Name
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.
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.
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
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.
Mementopatternisusedtorestorestateofanobjecttoapreviousstate. It is also
Memento
known as snapshot 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.
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
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
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 -
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.
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.
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
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.
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.
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