0% found this document useful (0 votes)
119 views5 pages

Comp 2911 Cheat Sheet

This document discusses several topics related to object-oriented programming and design patterns: 1. It defines UML diagrams like class diagrams and sequence diagrams. It also explains Class Responsibility Cards. 2. It covers object-oriented principles like inheritance, polymorphism, and the Liskov substitution and Demeter principles. 3. It defines common design patterns like composite, decorator, iterator, observer, and strategy patterns. 4. It compares reentrant locks and synchronized functions in Java and discusses issues like deadlocks.

Uploaded by

Jade Polanowski
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)
119 views5 pages

Comp 2911 Cheat Sheet

This document discusses several topics related to object-oriented programming and design patterns: 1. It defines UML diagrams like class diagrams and sequence diagrams. It also explains Class Responsibility Cards. 2. It covers object-oriented principles like inheritance, polymorphism, and the Liskov substitution and Demeter principles. 3. It defines common design patterns like composite, decorator, iterator, observer, and strategy patterns. 4. It compares reentrant locks and synchronized functions in Java and discusses issues like deadlocks.

Uploaded by

Jade Polanowski
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/ 5

Amalgamationofknowledge

Question1
CRC,UML
UML

SequenceDiagram

CRC(ClassResponsibilityCard/CollaboratorCard)

inUML,
|classcontainingvariable|<>|Classofthatvariable|
closedarrowisinheritance.
|subclass||>|superclass|
or
|class||>|interface|

Question2
ProgrammingbyContract&Inheritance
Lisekovprinciple:Thesubclasseshavetobeabletobeswappedoutforasuperclass
andeverythingshouldbehaveasnormal

Itstatesthat,inacomputerprogram,ifSisasubtypeofT,thenobjectsoftypeTmaybereplacedwith
objectsoftypeS(i.e.,objectsoftypeSmaysubstituteobjectsoftypeT)withoutalteringanyofthedesirable
propertiesofthatprogram(correctness,taskperformed,etc.).

Demeterprinciple:Notransitivity.IfGooglehasadealwithAppleandknowsitsnet
earnings,andApplehasanotherdealwithMicrosoftandknowsmicrosoftsnetearnings,
GoogleshouldnotbeabletofindoutanythingaboutMicrosoftthroughitsdealwith
Apple.
Inthiscase,anobject
A
canrequestaservice(callamethod)ofanobjectinstance
B
,
butobject
A
shouldnot"reachthrough"object
B
toaccessyetanotherobject,
C
,to
requestitsservices.
Equalsfunction:publicbooleanequals(Objectobj)
if(this==obj)returntrue

if(obj==null)returnfalse
if(getClass()!=obj.getClass())returnfalse
ClassNameOfThingother=(ClassNameOfThing)obj
Thencheckyomembervariables

Question3
GenericTypesandPolymorphism
SimilartothelabwithSet<E>orGraph<E>.

Covariance:Birdslayeggs.Morespecifically,aducklaysaduckegg.
WecanbemorespecificonthelefthandsideandsayaDucklaysanegg,
butwecantbemorespecificontherighthandsideandsayabirdlaysaduckegg.
LHScangetmorespecificandstillequalRHS.(Requiremore)

Contravariance:UnistudentscanwriteinC,Java,HTML,Python,etc.Webdesigners
canwriteinHTML.
WecanbelessspecificontheRHSandsayUnistudentscanwriteinHTML,
butWebdesignerscantwriteinC,Java,HTML,Python,etc.
RHScangetlessspecificandstillequalLHS.(Requireless)

Covariance:
class
Super{
ObjectgetSomething(){} }

class
Sub
extends
Super{
StringgetSomething() {} }

Sub#getSomethingiscovariantbecauseitreturnsasubclassofthereturntypeof
Super#getSomething(butfullfillsthecontractofSuper.getSomething())
Contravariance
class
Super
{
voiddoSomething(
Stringparameter) }

class
Sub
extends
Super
{
voiddoSomething(
Objectparameter) }

Sub#doSomethingiscontravariantbecauseittakesaparameterofasuperclassofthe
parameterofSuper#doSomething(but,again,fullfillsthecontractofSuper#doSomething)
Question4
DesignPatterns
Compositepattern
:Insteadofsayingifobjclassisrectangle,dothis,ifcircledothis,
blahblahblah,maketherectangleandcircleclassesimplementationsofaShapeclass,
andthenjustneedtocallShape.doThing(),wherehereShapeisaninterface.
NeedtouseINTERFACE
Decoratorpattern
:Useanabstractclass,butinsteadofitbeingaproblemwithworking
down,thistimeitissoyoucandodifferentthingswiththem.Likethestrategypattern.
Soyoucanmakeanewshapethatiscolouredinred,orashapethatiscolouredin

green,ortheoriginalplainshape.Theupsideisthatyoustillgetallthefunctionalityof
theplainshape,butyouhavetheaddedfunctionalityofthenewdecoratedclasses.
Howto:
Abstractclass(decorator)implementsbaseinterface(shape)andiscalledby
concretetypesbelow(rectangle,circle)andconcretetypesabove(redshape,
blueshape).
INTERFACE>ABSTRACTCLASS
Iteratorpattern:
implementanIteratorclassinsidetheiterableobjectclasswith
functionsfirst,next,is_doneandcurrent_item.Theobjectalsohasacreate_iterator
function.ThisissothatyoucancallObject.Iteratori=object.create_iterator()(which
returnstheiterableversionoftheobject)andtheni.first()willstart/initialise,i.next()islike
i++,i.current_item()returnsthevalue,Etc,etc.
NOTE:membervariableiniteratorclassis
privatejava.util.IteratoriteratorMemberVariable
andthishasfunction

iteratorMemberVariable.next()
whichshouldbeusedlike

try{

current=iteratorMemberVariable.next()

catch(NoSuchElementExceptionex){

current=999

}
Observerpattern
:Haveaninterface(AlarmListener)andtheninyourmainsystem,
haveanarrayoflistenerswhoneedtobeupdatedifsomethinghappens.Therewill
needtobearegisterfunctiontoaddthemtothealertsystem.AsoundAlarmfunction
runsthrougheachlistenerinthearrayandcalls((AlarmListener)e.next()).alarm().Each
listenerimplementstheAlarmListenerinterface.
NeedtouseINTERFACE
Strategypattern:

SurpriseQuestion
Locksandsynchronisation
ReentrantlocksvsSynchronizedfunctions
:Reentrantlockshaveextended
capabilities

Theabilitytohavemorethanoneconditionvariablepermonitor.Monitorsthat
usethesynchronizedkeywordcanonlyhaveone.Thismeansreentrantlocks
supportmorethanonewait()/notify()queue.

Theabilitytomakethelock"fair"."[fair]locksfavorgrantingaccesstothe
longestwaitingthread.Otherwisethislockdoesnotguaranteeanyparticular
accessorder."Synchronizedblocksareunfair.

Theabilitytocheckifthelockisbeingheld.

Theabilitytogetthelistofthreadswaitingonthelock.

Badthingsaboutreentrantlocks:
Needtoaddimportstatement.

Needtowraplockacquisitionsinatry/finallyblock.Thismakesitmoreuglythan
thesynchronizedkeyword.

Thesynchronizedkeywordcanbeputinmethoddefinitionswhichavoidsthe
needforablockwhichreducesnesting.

Lockcode:
finalLocklock=newReentrantLock()//CreatethelockfortheBoundedQueue
finalConditionfull=lock.newCondition()//Usedforproducerwaitingwhenqueueisfull

//Howtousecondition
function(Locklock,Conditionfull)
if(full){//Ifthebufferisfullweneedtosleep
full.await()//Releasethelockandwaituntilitisreturnedtous
}

Ifa
FUNCTION
isdeclaredsynchronised,itisavailabletoonlyoneobjectatatime
Thedatacanstillbeaccessedthough,justnotthefunction
Whileathreadiswaitingonalock,itdoesnotdoanythingelse(unlessreentrancelock).
Theotherthreadsstillcontinuetoworkthough
Deadlockoccursifathreadiswaitingonalock,andtheotherthreadisalsowaitingona
lock.Ex,ifmaincallsthread1Function,therewillbeadeadlock.
sychronizedthread1Function(){
thread2Function()
}

synchronizedthread2Function(){
thread1Function()
}

You might also like