Uploaded by Supun Jayasundara

Advanced Programming

advertisement
Higher Nationals
Internal verification of assessment decisions – BTEC (RQF)
INTERNAL VERIFICATION – ASSESSMENT DECISIONS
Programme title
HND in Computing - Application Dev / Software Eng. Pathway
Assessor
Internal
Verifier
Unit(s)
Unit 20 – Advance Programming
Assignment title
Student’s name
List which assessment
Pass
Merit
Distinction
criteria the Assessor has
awarded.
INTERNAL VERIFIER CHECKLIST
Do the assessment criteria awarded
match those shown in the assignment
Y/N
brief?
Is the Pass/Merit/Distinction grade awarded
justified by the assessor’s comments on the
Y/N
student work?
Has the work been assessed
accurately?
Y/N
Is the feedback to the student:
Give details:
• Constructive?
Y/
• Linked to relevant assessment criteria?
N
• Identifying opportunities for
Y/
improved performance?
• Agreeing actions?
N
Y/
N
Y/N
Does the assessment decision need
amending?
Assessor signature
Y/N
Date
Internal Verifier signature
Date
Programme Leader signature (if required)
Date
Higher Nationals - Summative Assignment Feedback Form
Student Name/ID
Unit Title
Assignment Number
Assessor
Date Received
Submission Date
1st submission
Date Received 2nd
Re-submission Date
submission
Assessor Feedback:
LO1. Examine the key components related to the object orientated programming paradigm,
analysing design pattern types.
Pass, Merit & Distinction Descripts
P1
M1
D1
M2
D2
M3
D3
LO2. Design a series of UML class diagrams
Pass, Merit & Distinction Descripts
P2
LO3. Implement code applying design patterns
Pass, Merit & Distinction Descripts
P3
LO4. Investigate scenarios with respect to design patterns
Pass, Merit & Distinction Descripts
Grade:
Assessor Signature:
P4
M4
D4
Date:
Resubmission Feedback:
Grade:
Assessor Signature:
Internal Verifier’s Comments:
Signature & Date:
Date:
* Please note that grade decisions are provisional. They are only confirmed once internal and external
moderation has taken place and grades decisions have been agreed at the assessment board.
Assignment Feedback
Formative Feedback: Assessor to Student
Action Plan
Summative feedback
Feedback: Student to Assessor
Assessor
Date
signature
Student
signature
Date
Pearson Higher Nationals in
Computing
Unit 20 – Advance
Programming
General Guidelines
1. A Cover page or title page – You should always attach a title page to
your assignment. Use previous page as your cover sheet and make sure
all the details are accurately filled.
2.
Attach this brief as the first section of your assignment.
3. All the assignments should be prepared using a word processing software.
4. All the assignments should be printed on A4 sized papers. Use single side printing.
5. Allow 1” for top, bottom , right margins and 1.25” for the left margin of each page.
Word Processing Rules
1. The font size should be 12 point, and should be in the style of Time New Roman.
2. Use 1.5 line spacing. Left justify all paragraphs.
3. Ensure that all the headings are consistent in terms of the font size and font style.
4. Use footer function in the word processor to insert Your Name,
Subject, Assignment No, and Page Number on each page. This is
useful if individual sheets become detached for any reason.
5. Use word processing application spell check and grammar check
function to help editing your assignment.
Important Points:
1. It is strictly prohibited to use textboxes to add texts in the assignments,
except for the compulsory information. eg: Figures, tables of
comparison etc. Adding text boxes in the body except for the before
mentioned compulsory information will result in rejection of your work.
2. Carefully check the hand in date and the instructions given in the
assignment. Late submissions will not be accepted.
3. Ensure that you give yourself enough time to complete the assignment by the due
date.
4. Excuses of any nature will not be accepted for failure to hand in the work on time.
5. You must take responsibility for managing your own time effectively.
6. If you are unable to hand in your assignment on time and have valid
reasons such as illness, you may apply (in writing) for an extension.
7. Failure to achieve at least PASS criteria will result in a REFERRAL grade.
8. Non-submission of work without valid reasons will lead to an automatic RE
FERRAL. You will then be asked to complete an alternative assignment.
9. If you use other people’s work or ideas in your assignment, reference them properly
using HARVARD referencing system to avoid plagiarism. You have to provide both
in-text citation and a reference list.
10. If you are proven to be guilty of plagiarism or any academic misconduct, your grade
could be reduced to A REFERRAL or at worst you could be expelled from the course
Student Declaration
I hereby, declare that I know what plagiarism entails, namely to use another’s work and to present
it as my own without attributing the sources in the correct form. I further understand what it means
to copy another’s work.
1. I know that plagiarism is a punishable offence because it constitutes theft.
2. I understand the plagiarism and copying policy of Edexcel UK.
3. I know what the consequences will be if I plagiarise or copy another’s work in
any of the assignments for this program.
4. I declare therefore that all work presented by me for every aspect of my
program, will be my own, and where I have made use of another’s work,
I will attribute the source in the correct way.
5. I acknowledge that the attachment of this document signed or not,
constitutes a binding agreement between myself and Pearson, UK.
6. I understand that my assignment will not be considered as submitted if
this document is not attached to the assignment.
Student’s Signature:
Date:
(Provide E-mail ID)
(Provide Submission Date)
Higher National Diploma in Business
Assignment Brief
Student Name /ID Number
Unit Number and Title
Unit 20 – Advance Programming
Academic Year
20021/22
Unit Tutor
Assignment Title
Issue Date
Submission Date
IV Name & Date
Submission format
The submission is in the form of an individual written report about. This should be
written in a concise, formal business style using single spacing and font size 12. You
are required to make use of headings, paragraphs and subsections as appropriate, and all
work must be supported with research and referenced using the Harvard referencing
system. Please also provide an end list of references using the Harvard referencing
system. Please note that this is an activity-based assessment where your document
submission should include evidences of activities carried out and of team working. To
carry out activities given on the brief, you are required to form groups, comprising not
exceeding 15 individuals.
The recommended word count is 4,000–4,500 words for the report excluding annexures.
Note that word counts are indicative only and you would not be penalised for exceeding
the word count.
Unit Learning Outcomes:
Learning Outcomes
By the end of this unit students will be able to:
LO1. Examine the key components related to the object-orientated
programming paradigm, analysing design pattern types.
LO2. Design a series of UML class diagrams.
LO3. Implement code applying design
patterns.
LO4 Investigate scenarios with respect to design patterns.
Assignment Brief and
Guidance:
BOC Software solutions is leading software company in Kandy as system analyst you
have to build an application for Family Dental Care (FDC) considering given scenario.
Family Dental Care (FDC) is a leading up market dental surgery located in Kandy. It
provides all types of dental treatments to patients which include extractions, nerve
fillings, maxillofacial surgeries (i.e. surgeries involving jaw bone) and sophisticated
dental implants. It is visited by prominent dentists and dental consultants with post
graduate qualifications, some of whom are working at the Faculty of Dental Science at
the University of Peradeniya.
Patients consult doctors by appointment. On their first visit, patients are required to
register by entering their personal details such as name, address, national identity card
number and contact number. A small fee is charged from the patient during registration.
A separate fee is charged for each treatment given.
Doctors too must get registered at FDC by providing personal details such as name,
address, date of birth, national ID number and contact number. In addition, consultants
must provide the name of their post graduate qualification along with the country of the
University that granted it and ordinary dentists should indicate the number of years of
experience.
FDC consists of four fully equipped surgery rooms so that four patients can be
accommodated at any given time. FDC also contains a dental scan room which can be
attended by one patient at a time. The dental scan machine is operated by one of the
dentists of the FDC facility. Normally, a dentist without appointments for a given time
slot (say, between 5 PM and 6 PM) is assigned to the machine by the manager. When
that time slot finishes, another doctor who is free will be assigned.
The staff of FDC is made up of a manager, four nurses (one for each of the four
surgery rooms) and a receptionist who handles registrations and appointments.
An information system is required to keep track of patients, doctors, appointments,
treatments given to patients and payments. The system must also maintain information
about the staff. It has been decided to use an object oriented approach to design and
implement the system.
Task 1
Examine the Object oriented concepts given below. Provide diagrams and code snippets from
suitable specific programming language to supplement your explanations.
i)
Class
ii)
Object
iii)
Message
iv)
Encapsulation
v)
Inheritance
vi)
Polymorphism
vii)
Aggregation/composition
Task 2
Design and build the detailed UML class diagram for the Family Dental Care system. Your
solution should demonstrate all inter-class relationships namely Association, Inheritance and
Aggregation/composition. The classes should include attributes and methods needed.
Draw the class diagram for the explained system. Including all notations and details and ensure
that the diagram has the required functionalities. Analyze the class diagram provided above
and derive code scenarios related to the UML diagram.
Task 3
Determine and briefly discuss the range of design patterns and describe at least one design
pattern from the three available types of design pattern. Provide suitable UML diagrams for
the given patterns and analyze the relationship between object-oriented paradigm and design
patterns providing a suitable example.
Task 4
Scenario 1
FDC owns a very expensive, state of the art dental scan machine (a device far superior to a
traditional dental X-ray machine) manufactured by Toshiba, Japan. FDC will be own just one
such machine in the foreseeable future. When modeling and implementing FDC system in
software, you must ensure that only one instance of that machine is created.
You may include suitable attributes for the machine such as serial number, make, country of
origin and cost. Implementation should allow the user to enter details of the dental scanner and
create the sole instance of that machine.
Scenario 02
Below table provides the hierarchy of the Employees and their monthly salary in FDC
Emp Id
Name
Position
Salary
A001
Anton
Director
1,000,000 LKR
A002
Chamod
Dentist
600,000 LKR
A003
Supuni
Dentist
600,000 LKR
A004
Madhavi
Dentist
600,000 LKR
A005
Piyal
Nurse
200,000 LKR
A006
Kamal
Nurse
200,000 LKR
A007
Kapila
Nurse
200,000 LKR
All the Nurses are working under the Dentists and Chamod(Dentist) is working under the
Supuni(Dentist) and Madhavi(Dentist) is working under the Anton(Director).
Develop a system to display the details of all employees and your system should display which
employee is working under which employee clearly.
Scenario 03
Patients who need dental scans are kept in a First in First Out queue. Assume that you have found an
already developed Queue container in a software library. It provides standard queue operations to insert
and remove data (known as enqueue and deque respectively). However, you need some specific
operations such as search() to look up a particular patient and showAll() to list all the patients in the
queue. These additional operations are not provided by the library unit.
For each of the above scenarios:
Select and Justify the most appropriate design pattern for each of the above given scenarios then Define
and Draw class diagrams for above mentioned design patterns and develop code for the above scenarios
(except for the 3rd Scenario) using an appropriate programming language. Critically evaluate why you
selected the above design patterns and compare your answer with the range of design patterns available.
Grading Rubric
Grading Criteria
LO1 Examine the key components related
to the
object-orientated programming
paradigm,
analyzing design pattern types
P1 Examine the characteristics of the
object-orientated paradigm as well as the various
class relationships.
M1 Determine a design pattern from each of
the creational, structural and behavioral pattern
types.
D1 Analyse the relationship between the
object-orientated paradigm and design patterns.
LO2 Design a series of UML class diagrams
P2 Design and build class diagrams using a UML
tool.
M2 Define class diagrams for specific design patterns
using a UML tool.
D2 Analyse how class diagrams can be
derived from a given code scenario using
a UML tool.
LO3 Implement code applying design
patterns
P3 Build an application derived from UML class
diagrams.
M3 Develop code that implements a design pattern
for a given purpose.
D3 Evaluate the use of design patterns for the given
purpose specified in M3.
Achieved
Feedback
LO4 Investigate scenarios with respect to design
Patterns
P4 Discuss a range of design patterns with
relevant examples of creational, structure and
behavioral pattern types.
M4 Reconcile the most appropriate design
pattern from a range with a series of given scenarios.
D4 Critically evaluate a range of
design patterns against the range of
given scenarios with justification of
your choices.
Contents
1.1 Examine the object-oriented concepts ....................................................................................... 23
1.1.1Object Oriented Concept ...................................................................................................... 23
1.1.2
Introduction to Class ..................................................................................................... 24
1.1.3
Introduction to Object .................................................................................................. 25
1.1.4
Introduction to Method ................................................................................................ 28
1.1.7Abstraction ............................................................................................................................ 36
1.1.8Encapsulation ........................................................................................................................ 40
2.3.
Inheritance ............................................................................................................................ 60
2.4.
Composition .......................................................................................................................... 60
2.5.
Multiplicity ............................................................................................................................ 60
2.6.
Developed Family Dental Care system for the scenario ....................................................... 61
3.1.
Determine and briefly discuss the range of design patterns ................................................ 72
3.1.1 Gang of four (GoF) ............................................................................................................... 72
3.1.2 Structure of a Design Pattern............................................................................................... 73
3.1.3 Category of GOF design pattern and their purpose............................................................. 73
3.1.4 Creational Design Patterns .................................................................................................. 75
3.2. Analyze the relationship between object-oriented paradigm and design patterns ................ 101
4.
Task 04 ........................................................................................................................................ 102
4.1 Scenario 1.................................................................................................................................. 102
4.1.1.
Choose design pattern for scenario 1 ......................................................................... 102
4.1.2.
Comparison among design patterns ........................................................................... 102
4.2 Scenario 2.................................................................................................................................. 104
4.2.1 Choose design pattern for second scenario....................................................................... 105
4.2.2 Comparison among the design patterns............................................................................ 105
4.3 Scenario 3.................................................................................................................................. 108
4.3.1. Choose design pattern for third scenario ......................................................................... 108
Figure 1: Class --------------------------------------------------------------------------------------------------------------- 24
Figure 2: Syntax For Class------------------------------------------------------------------------------------------------- 25
Figure 3:Code for creating class----------------------------------------------------------------------------------------- 25
Figure 4:5 Example for Object ------------------------------------------------------------------------------------------- 26
Figure 5: Code for creating object -------------------------------------------------------------------------------------- 27
Figure 6: Output ------------------------------------------------------------------------------------------------------------ 27
Figure 7:Syntax for method ---------------------------------------------------------------------------------------------- 28
Figure 8:Syntax for method ---------------------------------------------------------------------------------------------- 29
Figure 9: Output ------------------------------------------------------------------------------------------------------------ 29
Figure 10:Code for non-static method -------------------------------------------------------------------------------- 29
Figure 11: Output----------------------------------------------------------------------------------------------------------- 29
Figure 12:Image for static and non-static ---------------------------------------------------------------------------- 30
Figure 13:Example code for final method ---------------------------------------------------------------------------- 31
Figure 14: Output----------------------------------------------------------------------------------------------------------- 31
Figure 15:Code for abstract method----------------------------------------------------------------------------------- 32
Figure 16:Output ----------------------------------------------------------------------------------------------------------- 32
Figure 17:Code for normal method ------------------------------------------------------------------------------------ 32
Figure 18:Method calling loop ------------------------------------------------------------------------------------------ 33
Figure 19:Code for method calling ------------------------------------------------------------------------------------- 33
Figure 20: Output----------------------------------------------------------------------------------------------------------- 34
Figure 21:Message Implementation ----------------------------------------------------------------------------------- 35
Figure 22:Object oriented concepts ----------------------------------------------------------------------------------- 36
Figure 23:Example image with and without abstraction --------------------------------------------------------- 37
Figure 24:Syntax for abstract class ------------------------------------------------------------------------------------- 38
Figure 25:Code for abstract class implementation ----------------------------------------------------------------- 38
Figure 26:Output ----------------------------------------------------------------------------------------------------------- 38
Figure 27:Code for abstract interface --------------------------------------------------------------------------------- 39
Figure 28:Output ----------------------------------------------------------------------------------------------------------- 39
Figure 29:Encapsulation -------------------------------------------------------------------------------------------------- 40
Figure 30:Code for encapsulation with person class -------------------------------------------------------------- 41
Figure 31:Main class ------------------------------------------------------------------------------------------------------- 41
Figure 32:Output ----------------------------------------------------------------------------------------------------------- 42
Figure 33:Example of Inheritance -------------------------------------------------------------------------------------- 42
Figure 34:Syntax for inheritance ---------------------------------------------------------------------------------------- 43
Figure 35:Code for inheritance------------------------------------------------------------------------------------------ 43
Figure 36:Output ----------------------------------------------------------------------------------------------------------- 44
Figure 37:Example of single level inheritance ----------------------------------------------------------------------- 45
Figure 38:Code for single level inheritance -------------------------------------------------------------------------- 45
Figure 39:Output ----------------------------------------------------------------------------------------------------------- 45
Figure 40:Multilevel inheritance ---------------------------------------------------------------------------------------- 46
Figure 41:Code for multilevel inheritance ---------------------------------------------------------------------------- 46
Figure 42:Code for multilevel inheritance ---------------------------------------------------------------------------- 47
Figure 43:Hierarchical level inheritance ------------------------------------------------------------------------------ 47
Figure 44:Code for Hierarchical level inheritance ------------------------------------------------------------------ 47
Figure 45:Output ----------------------------------------------------------------------------------------------------------- 48
Figure 46:Multiple Inheritance ------------------------------------------------------------------------------------------ 48
Figure 47:Code for Multiple inheritance ------------------------------------------------------------------------------ 49
Figure 48:Code for Multiple inheritance ------------------------------------------------------------------------------ 49
Figure 49:Hybrid inheritance -------------------------------------------------------------------------------------------- 50
Figure 50:Code for Hybrid inheritance -------------------------------------------------------------------------------- 50
Figure 51: Output----------------------------------------------------------------------------------------------------------- 51
Figure 52:Code for runtime polymorphism -------------------------------------------------------------------------- 52
Figure 53:Output ----------------------------------------------------------------------------------------------------------- 52
Figure 55:Code for compile time polymorphism ------------------------------------------------------------------- 53
Figure 54:Output ----------------------------------------------------------------------------------------------------------- 53
Figure 56:Example of aggregation relationship in OOP ----------------------------------------------------------- 54
Figure 57:Code for aggregation relationship ------------------------------------------------------------------------ 55
Figure 58:Output ----------------------------------------------------------------------------------------------------------- 55
Figure 59:Example of composition relationship in OOP ---------------------------------------------------------- 56
Figure 60:Code for composition relationship in OOP -------------------------------------------------------------- 56
Figure 61:Output ----------------------------------------------------------------------------------------------------------- 57
Figure 62:UML Diagram types ------------------------------------------------------------------------------------------- 58
Figure 63: Class diagram for FDC --------------------------------------------------------------------------------------- 59
Figure 64:Login Form ------------------------------------------------------------------------------------------------------ 61
Figure 65:Validation for textbox ---------------------------------------------------------------------------------------- 61
Figure 66:Validation message ------------------------------------------------------------------------------------------- 61
Figure 67:Login for manager --------------------------------------------------------------------------------------------- 62
Figure 68:Login for receptionist ---------------------------------------------------------------------------------------- 62
Figure 69:Dashboard by manager -------------------------------------------------------------------------------------- 63
Figure 70:Dashboard by receptionist ---------------------------------------------------------------------------------- 63
Figure 71:Doctor Registration by manager -------------------------------------------------------------------------- 64
Figure 72:Doctor Registration by receptionist ---------------------------------------------------------------------- 64
Figure 73:Patient registration ------------------------------------------------------------------------------------------- 65
Figure 74:Appointment --------------------------------------------------------------------------------------------------- 65
Figure 75:Room allocation ----------------------------------------------------------------------------------------------- 66
Figure 76: Staff registration ---------------------------------------------------------------------------------------------- 66
Figure 77:Add Code -------------------------------------------------------------------------------------------------------- 67
Figure 78:Update Code --------------------------------------------------------------------------------------------------- 67
Figure 79: Delete Code ---------------------------------------------------------------------------------------------------- 67
Figure 80:Abstract class --------------------------------------------------------------------------------------------------- 67
Figure 81:Info table extends table class ------------------------------------------------------------------------------ 68
Figure 82:Called abstract method -------------------------------------------------------------------------------------- 68
Figure 83:Class creation -------------------------------------------------------------------------------------------------- 69
Figure 84:Set values ------------------------------------------------------------------------------------------------------- 69
Figure 85:Called getter methods --------------------------------------------------------------------------------------- 69
Figure 86:Polymorphism code example ------------------------------------------------------------------------------ 70
Figure 87:Inheritance code example ---------------------------------------------------------------------------------- 71
Figure 88:Design pattern categorize ----------------------------------------------------------------------------------- 72
Figure 89:Creational design patterns ---------------------------------------------------------------------------------- 75
Figure 90:UML Diagram of creation design patter ----------------------------------------------------------------- 76
Figure 91:UML diagram of singleton pattern ------------------------------------------------------------------------ 77
Figure 92:SingleObject.java ---------------------------------------------------------------------------------------------- 78
Figure 93:SingletonPatternDemo.java -------------------------------------------------------------------------------- 78
Figure 94:Output ----------------------------------------------------------------------------------------------------------- 78
Figure 95:Eager Initialized Singleton----------------------------------------------------------------------------------- 79
Figure 96:Lazy Initialized Singleton ------------------------------------------------------------------------------------ 79
Figure 97:Example UML diagram of factory pattern Implementation ---------------------------------------- 80
Figure 98:Shape.java ------------------------------------------------------------------------------------------------------ 81
Figure 99:Rectangle.java-------------------------------------------------------------------------------------------------- 81
Figure 100:Square.java ---------------------------------------------------------------------------------------------------- 81
Figure 101:Circle.java------------------------------------------------------------------------------------------------------ 81
Figure 102:ShapeFactory.java ------------------------------------------------------------------------------------------- 82
Figure 103:FactoryPatternDemo.java --------------------------------------------------------------------------------- 82
Figure 104:Output ---------------------------------------------------------------------------------------------------------- 83
Figure 105:Example UML diagram of abstract factory pattern ------------------------------------------------- 84
Figure 106:Shape.java ----------------------------------------------------------------------------------------------------- 84
Figure 107:Rectangle.java ------------------------------------------------------------------------------------------------ 84
Figure 108:Square.java ---------------------------------------------------------------------------------------------------- 85
Figure 109:Circle.java------------------------------------------------------------------------------------------------------ 85
Figure 110:Color.java ------------------------------------------------------------------------------------------------------ 85
Figure 111:Red.java -------------------------------------------------------------------------------------------------------- 85
Figure 112:Green.java ----------------------------------------------------------------------------------------------------- 86
Figure 113:Blue.java ------------------------------------------------------------------------------------------------------- 86
Figure 114:AbstractFactory.java ---------------------------------------------------------------------------------------- 86
Figure 115:ShapeFactory.java ------------------------------------------------------------------------------------------- 87
Figure 116:ColorFactory.java -------------------------------------------------------------------------------------------- 87
Figure 117:FactoryProducer.java --------------------------------------------------------------------------------------- 88
Figure 118:AbstractFactoryPatternDemo.java ---------------------------------------------------------------------- 88
Figure 119:Output ---------------------------------------------------------------------------------------------------------- 89
Figure 120:Employee.java ------------------------------------------------------------------------------------------------ 89
Figure 121: Output --------------------------------------------------------------------------------------------------------- 90
Figure 122:UML diagram for composite pattern ------------------------------------------------------------------- 92
Figure 123:Family.java ---------------------------------------------------------------------------------------------------- 93
Figure 124:CompositePatternFamily.java ---------------------------------------------------------------------------- 93
Figure 125:Output ---------------------------------------------------------------------------------------------------------- 94
Figure 126:UML Diagram of iterator pattern ------------------------------------------------------------------------ 96
Figure 127:Iterator.java --------------------------------------------------------------------------------------------------- 96
Figure 128:Iterable.java--------------------------------------------------------------------------------------------------- 96
Figure 129:ProductCatalog.java----------------------------------------------------------------------------------------- 97
Figure 130:IteratorPatternExample.java------------------------------------------------------------------------------ 97
Figure 131:Output of iterator ------------------------------------------------------------------------------------------- 97
Figure 132:UML diagram of observer pattern----------------------------------------------------------------------- 98
Figure 133:Subject.java --------------------------------------------------------------------------------------------------- 99
Figure 134:Observer.java ------------------------------------------------------------------------------------------------- 99
Figure 135:Rectangle1.java -------------------------------------------------------------------------------------------- 100
Figure 136:Rectangle2.java -------------------------------------------------------------------------------------------- 100
Figure 137:ObserverPatternRectangle.java ------------------------------------------------------------------------ 100
Figure 138:Output -------------------------------------------------------------------------------------------------------- 101
Figure 139:Class diagram ----------------------------------------------------------------------------------------------- 103
Figure 140:Fist class creation ------------------------------------------------------------------------------------------ 103
Figure 141:Continue ----------------------------------------------------------------------------------------------------- 104
Figure 142:Main class --------------------------------------------------------------------------------------------------- 104
Figure 143:Output of scan machine creation ---------------------------------------------------------------------- 104
Figure 144:Class diagram of Employees ---------------------------------------------------------------------------- 106
Figure 145:Employees.java--------------------------------------------------------------------------------------------- 107
Figure 146:CompositePatternFDC.java ----------------------------------------------------------------------------- 107
Figure 147:Continue ----------------------------------------------------------------------------------------------------- 108
Figure 148:Output of employee’s hierarchy ----------------------------------------------------------------------- 108
Figure 149:Class diagram of third scenario ------------------------------------------------------------------------ 109
1. Task 01
1.1 Examine the object-oriented concepts
1.1.1Object Oriented Concept
A programming paradigm known as object-oriented programming (OOP) centers software design
around data rather than functions and logic. A data field having unique features and behavior is called
an object.
Instead than concentrating on the logic needed to control the objects, object-oriented programming
(OOP) concentrates on the objects that developers want to handle. Big, complex, and regularly updated
or maintained projects are best suited for this type of programming. This includes mobile applications
as well as design and manufacturing software; for instance, OOP can be used to model manufacturing
systems. (Lewis, 2022)
OOPS'S CONCEPTS
Object
Class
Method
Abstraction
Encapsulation
Inheritance
Polymorphism
1.1.1.1. Advantage of OOPS
1. OOP implements real life scenario.
2. OOP provides a clear modular structure for programs.
3. Easy to maintain and transform existing code because new objects can be created with
4. small differences to current ones.
5. Programs are divided into objects.
6. Data is hidden and cannot be accessed by external functions without permission.
7. Objects may communicate with each other through functions.
8. New data and functions can be easily added whenever necessary
1.1.1.2. Disadvantage of OOPS
1. Proper planning and design are required before programming using OOPs technique.
2. Program design is trickily.
1.1.2
Introduction to Class
Classes are like object constructors for creating objects. The collection of objects is said to be a class.
Class is also called a template or blueprint of an object. Classes have members which can be fields,
methods. A class has both static and instance initializers. (Help, 2022)
Figure 1: Class
The above image is briefly outlined that person as a class which has characteristics like name, age,
gender so on. And its behavior like walk, eat, sleep etc. these belong to class.
The components of the Java Class declaration are:
Fist user should declare Access Modifiers that can access in Java classes using any access modifiers
such as public, private, protected and default.
Second is Class Name that the class name generally represents nouns which should begin with a capital
letter without any spaces.
Third is Superclass (if there is a need). The name of the parent class is a superclass and its child class
is a subclass, and child class inherits the properties of a parent using the “extends” keyword. A subclass
can only inherit a single parent.
Fifth is Interfaces (if there is a need) that declare an interface, user just write the keyword interface
followed by the interface name.
Final is Class Body. The class body follows the class declaration and embeds within curly braces {}.
Figure 2: Syntax For Class
Thinking of the class as an identity of a member. It contains all the details about the name, age and so
on. Based on these descriptions we find the member. Member is the class. The class has attributes like
name and age. And its functionalities revolve around class and object. It is contained object because
object interact with each other by calling method.
Figure 3:Code for creating class
In Java, a class is as important as breathing a human to stay alive. It is the most basic unit of Objectoriented programming. All of the declaration exists inside of class in java.
Advantage of using class
1. Classes support a powerful programming model by encapsulating related functionality
2. into objects.
3. Classes enhance code reuse.
4. Classes provide strong typing that enables to do compile-time checking in order to catch
5. errors before the code is deployed or executed.
6. Classes help to take all the properties and behaviors of an object in program, and
7. combine them into a single template.
1.1.3
Introduction to Object
An object is a member (also called an instance) of a class. Each object has an identity, a behavior and a
state. The state of an object is stored in fields (variables), while methods (functions) display the object's
behavior. (Rabelo, 2021)
Figure 4:5 Example for Object
Identity: is a characteristic used to uniquely identify that object such as a random ID number or an
address in memory. For example: girl and boy.
States: are stored in fields that represent the individual characteristics of that object. For example: Boy
and girl may have name, age, and gender.
Behavior: is exposed through methods that operate its internal state. For example: Boy and girl
behaviors is like walk, eat, sleep, and run.
Objects are very similar to the object’s leaner can observe in the real world. Objects are also called a
run time entity of the world. If animals are class, dog and car are object of animals’ class.
Objects are self–contained which consists of methods and properties which makes data useful. Objects
can be both physical and logical data. It contains addresses and takes up some space in memory.
When user creates an object of a class, first, they need to specify the class name by using the class
keyword.
Below the image with class name is Member and it has attributes name and age. In java programming,
it calls these attributes as variables and behaviors as methods.
Figure 5: Code for creating object
The above image is briefly outlined that member as class that has attributes and methods. Here have
used the new keyword along with the constructor of the class to create object of male and female.
Constructors are similar to methods and have the same name as the class. Member () is the constructor
of the Member class. Inside the main class, have created two object. By using male and female object,
it can access the field and method of member class.
Figure 6: Output
More importantly, objects are abstract data types (that is, the behavior of objects is defined by a set of
values and operations).
1.1.4
Introduction to Method
A method is a block of code or collection of statements grouped together to complete a certain job or
operation. A method is used to achieve the reusability of code. A method is written once and can be
utilized many times. It also gives the easy modification and readability of code. A method is executed
only when user call or invoke it. Methods have two categories in programming such as pre-defined and
user defined. Predefined methods are the methods that are already defined in the Java class libraries.
When the particular method is written by the user or programmer, it is known as a user-defined method.
(Team, 2022)
Return-Type specifies the type of value that the return statement of the function returns. It may be any
valid data type. If no value is being returned, user can use the return type void as default.
Method name: is that the name of the method should be a valid identifier. The naming conventions
generally followed for method names should be meaningful and should begin with a lowercase letter.
For names having multiple names, user can use the camelCase naming convention.
For example: displayDetails, getMarks
The method name should basically begin with a verb followed by one or more nouns.
For example: displayData, findData, calculateAmount.
Method body: is that it includes the programming statements to be used to perform some tasks.
The method body is enclosed inside the curly braces {}.
Figure 7:Syntax for method
Methods are four type that are static method and final method
1.1.4.1Static method
Static method belongs to a class and not an object of a class. So, there is no need to create an object to
call it. A static method can also access static data member and can change the value of it. The static
method cannot use non-static data member and cannot call nonstatic method directly. Static method can
create by using the “static” keyword. More importantly, this and super keyword cannot be used in static
method.
Figure 8:Syntax for method
Figure 9: Output
1.1.4.2Non static method
The object method is a non-static method that belongs to the class and its object. Creating an object is
necessary to call the object method.
Figure 10:Code for non-static method
Figure 11: Output
Some important points between static and non-static method
1. Non static method memory is allocated multiple time whenever method is calling but memory for
static method is allocated only once at the time of class loading.
2. Non static is specific to an object so that these are also called as instance method, but static is
common to every object so that it is also called as class method.
3. Non static methods always access properties with object reference but static for properties always
access with class reference.
Below the image is represented that how the static and non-static properties are accessed in the
different static or non-static method of same class or other class.
Figure 12:Image for static and non-static
1.1.4.3 Final method
Final method is defined that if a method is with “final” keyword, it is known as final method. Then, the
method cannot be overridden in the subclasses. It is worked that the final method is to declare methods
of how’s definition cannot be changed by a child or subclass that extends it. As the parent class final
method was overridden by the child class final method that is not possible in the Java programming
language.
The method is created in java programming as final method to restrict the unwanted and improper use
of method definition while overriding the method.
Although it is not logically incorrect, it can change the meaning of the method and the learner might
interpret it wrongly. Therefore, in such cases to prevent the unwanted method definitions, programmer
declares methods as final.
Here make a class Animal and declare a non-final method soundAnimal() in it. Someone creates a Cat
class and overrides the soundAnimal() method in it and prints the wrong sound of the Cat such as Woof
or Roar. (TechVidvan, 2022)
The code will make the wrong use of method, so overcome this situation, can use the final method as
shown code below.
Figure 13:Example code for final method
Figure 14: Output
1.1.4.4 Abstract method
A method without implementation is known as abstract method. A method is always declared in an
abstract class. In other words, can say that if a class has an abstract method, it must be declared abstract.
It can declare an abstract method by using the “abstract” keyword.
Figure 15:Code for abstract method
Figure 16:Output
1.1.4.5 Normal method
Below the program is briefly outlined that member as a class. And it has attributes and methods. Here
have created methods talking and running for representing behavior of member class.
Figure 17:Code for normal method
1.1.4.6 Method call
When a program calls a method, program control is transferred to the called method. A called method
returns control to the caller when its return statement is executed or when its method ending closing
brace is reached.
Figure 18:Method calling loop
When the method is finished, execution returns to the area of the program code from which it was
called, and the program continues on to the next line of code. To call a method in Java, write the
method’s name followed by two parentheses () and a semicolon; as shown above.
Method calling are two ways that with arguments and without arguments. It means that an argument is
a value passed to a method when the method is called. Whenever any method is called during the
execution of the program there are some values passed with the method. These values are called
arguments. (Programming, 2021)
Figure 19:Code for method calling
The above code is briefly outlined that have created two methods named display1() and display2(). The
methods is with parameter and without parameter. It has created an object eCode for ExampleCode
because methods can access through the object of example code class.
Here have called two methods display1 without passing arguments and display2 with passing argument.
Figure 20: Output
1.1.5 Message
Message Passing in terms of computers is communication between processes. It is a form of
communication used in object-oriented programming as well as parallel programming. Message passing
in Java is like sending an object i.e. message from one thread to another thread. It is used when threads
do not have shared memory and are unable to share monitors or semaphores or any other shared
variables to communicate. Suppose we consider an example of producer and consumer, likewise what
producer will produce, the consumer will be able to consume that only. We mostly use Queue to
implement communication between threads.
In Producer there are two synchronized methods putMessage() which will call form run() method of
Producer and add message in Vector whereas getMessage() extracts the message from the queue for the
consumer.
Using message passing simplifies the producer-consumer problem as they don’t have to reference each
other directly but only communicate via a queue.
Object A
Methods
Data
Object B
Methods
Message
Data
Message
Message
Message
Object C
Methods
Data
Object D
Methods
Message
Data
Figure 21:Message Implementation
1.1.6
The concept of OOPS
Basically, object-oriented program supports four important characteristics that programmers use these
concepts help to implement the real-world problems when they are trying to solve with object oriented
program. (Lewis, 2022) These three concepts of Object oriented are:
1.
Abstraction.
2.
Encapsulation.
3.
Inheritance.
4.
Polymorphism.
Figure 22:Object oriented concepts
More importantly, the implicit characteristic of object-oriented concept is abstraction.
Programmers use it to specify new abstract data types.
1.1.7Abstraction
Abstraction is a mechanism of selecting only some necessary and essential properties or methods to
represent the object while hiding all the internal implementation details from user.
The abstraction helps to reduce the complexity of the design and implementation process of software.
There is two ways to obtain the abstraction feature in the software that are using an Abstract class or
using an Interface. An abstract class allows to group several related classes as siblings but it does not
support multiple inheritance like Interface. In the abstract class, programmer cannot be used to create
objects because abstract classes are restricted classes. The instance variables of an abstract class can be
accessed when it is inherited from another class. Abstract methods are methods present only in abstract
classes, which do not have a body. The body is provided by a subclass that inherits from the abstract
class. If a class has even one abstract method, it will call an abstract class. (Hartman, 2022)
Figure 23:Example image with and without abstraction
A man have got a car and he wish to drive his car. He only know how to drive a car but he cannot know
about how to works internal functionality of a car. As abstraction works in the same way, it shows only
important things to the use and hides internal details. There are two ways to achieve or implement
abstraction in java program using abstract classes and interfaces. Interfaces allow 100% abstraction
(complete abstraction) but abstract classes allow 0 to 100% abstraction (partial to complete abstraction).
Interfaces allow user to abstract the implementation completely but abstract classes can contain concrete
methods that have the implementation which results in a partial abstraction.
The important point between abstract class and interface
1. An abstract class can have abstract or non-abstract methods but interface can only have
abstract methods.
2. Interfaces can have final variables as default variables but abstract may or may not
contain the final variables.
3. An abstract class may provide interface implementation but Interfaces cannot
implement an abstract class.
4. An abstract class is inherited using the “extends” keyword but interface is
implemented using the “implements” keyword.
5. An abstract class can extend other classes or implement multiple interfaces but
interface can only implement another interface.
6. Interface members are by default public but abstract class can have private or protected
data members apart from public members.
1.1.7.1.
Abstract class
Figure 24:Syntax for abstract class
Figure 25:Code for abstract class implementation
The above code is briefly outlined that have a Bank class. In this class, have an abstract method,
getInterestRate (). Then it declares two classes BOC and NSB that inherit from the Bank class. Both
these classes implement the getInterestRate () method by returning their respective interest rates. Then
in the main method, create a bank object. First, the bank object contains an object of BOC class and
displays the interest rate. Next, the NSB object is created and it displays the interest rate.
Therefore, it can assume that the Bank class is a sort of a sketch or a structure that allows to get an
interest rate. From this structure, can create as many concrete classes as it wants, and then, can get the
respective interest rates for each bank object.
Figure 26:Output
1.1.7.2.Abstract interface
It is descripted that Interface looks like a class but it is not a class. An interface can have methods and
variables just like the class but the methods declared in interface are by default abstract. It means that
methods in interfaces do not have body. So, they have to be implemented by the class before it can
access them.
The class implements interface and it must implement all the methods of that interface. It is said that
java programming language does not allow to extend more than one class, however it can implement
more than one interfaces in class. All the interface methods are by default abstract and public.
An interface declaration is by using the interface keyword. It is pointed out that A class uses the
‘implements’ keyword to inherit an interface and an interface uses ‘extends’ keyword to inherit another
interface.
Figure 27:Code for abstract interface
The above image is shown that Bank interface has only one abstract method. Its implementation is
provided by BOC and NSB classes. Interface is defined here but implementation is provided by different
implementation providers. Here, the implementation part is hidden by the user which used the interface.
Figure 28:Output
1.1.8Encapsulation
Encapsulation is one of the most powerful and fundamental concepts of Object-Oriented Programming.
Encapsulation is the mechanism that binds together code and the data into a single unit and keeps both
from being safe from outside interference and misuse. In this process, the data is hidden from other
classes and can only be accessed using the methods of the current class. Hence, it is also known as data
hiding. Encapsulation acts as a protective wrapper that prevents the code and data from being accessed
by outsiders.
(Logic, 2022) encapsulation is achieved by the used of the keywords, private, public and
protected.
The public keyword
This keyword allows makes the method or attribute accessible both from inside and outside the class.
The private keyword
Attributes and methods declared as private can only be accessible by methods inside the class. They
can’t be accessible by external classes.
The protected Keyword
Attributes declared as protected can be accessed by from within the class and is also accessible by
derived from that class.
Figure 29:Encapsulation
To achieve encapsulation in Java
1. Declare the variables of a class as private.
2. Provide public setter and getter methods to modify and view the variables values.
Figure 30:Code for encapsulation with person class
The above code is briefly outlined that have three variables name, age and bank balance. Here have
created separate setter and getter methods for all the variables and used these variables inside the same
methods. Setter methods set the value of the variable, while Getter methods are used to get or return the
values.
Figure 31:Main class
Figure 32:Output
Advantage of Encapsulation
1. Encapsulation allows the programmer to hide the inner classes in programming and to give access
only to the desired codes to the users. Furthermore, it gives the facility to the developer to not allow
the users to know how the data and variables are stored.
2. There can access private members only within the same class. If there need to access these private
variables, programmer have to use public keyword for “setter” and
3. “getter” methods.
4. Encapsulation allows the programmer to effectively use the existing code again and again.
More importantly, there is a different between encapsulation and abstraction that encapsulation is a
principle to solve the issue at the implementation phase but the abstraction principle is to solve the
issue at the design phase.
1.1.9Inheritance
Inheritance allows new objects to be defined from existing objects. While this can be seen as a form
of code reuse, it also provides an extension mechanism: by inheriting code, programmer can change
the behavior of existing objects.
In the java programming, the idea behind inheritance is that user can create new classes that are built
upon existing classes. When user inherit from an existing class, they can reuse methods and fields of
the parent class. Moreover, user can add new methods and fields in their current class also.
Inheritance represents the IS-A relationship which is also known as a parent child relationship. In this
process, can manage the information in a hierarchical order with the use of inheritance. (Singh, 2022)
In addition, the class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class, parent class).
Figure 33:Example of Inheritance
A child inherits the features of its parents such as beauty or hair of mother and intelligence or
behavior of father as shown in the above.
Figure 34:Syntax for inheritance
Figure 35:Code for inheritance
In the above example of Inheritance, Currency is called parent class while Dollor is a child of Currency
class. It means Dollor inherits all non-private members such as fields and methods. The major reason
of inheritance that is used for code reusability. It means code once is written, can be used again and
again in the new classes.
Figure 36:Output
1.1.9.1 Types of Inheritance
On the basis of class, there can be three types of inheritance in java such as single, multilevel and
hierarchical but in java programming, multiple and hybrid inheritance is supported through interface
only because these belong to abstract class. (Singh, 2022)
1.1.9.2 Single level Inheritance
Single inheritance is that when a class extends another one class only then calls it a single inheritance.
The example is that class Student extends only one class which is Person. Here Person is a parent class
of Student and Student would be a child class of Person. (Singh, 2022)
Figure 37:Example of single level inheritance
Single level Inheritance is represented that a child and parent class relationship where one class
inherits another class.
Figure 38:Code for single level inheritance
Figure 39:Output
1.1.9.3 Multilevel Inheritance
When a class is derived from a class which is also derived from another class, for example. a class
having more than one parent class but at different levels, such type of inheritance is called Multilevel
Inheritance.
Figure 40:Multilevel inheritance
Here, class Student inherits the properties and behavior of class Person and class Software Engineer
inherits the properties of class Student. Class Person is the parent class for Student and class Student is
the parent class for Software engineer. So, class Software engineer implicitly inherits the properties and
methods of class Person along with Class Student.
Figure 41:Code for multilevel inheritance
Figure 42:Code for multilevel inheritance
1.1.9.4 Hierarchical level
In Hierarchical Inheritance in Java, more than one derived class inherits a single base class. It means
more than one child class inherits a single parent class or a single parent class has more than one child
class which called hierarchical inherence.
Figure 43:Hierarchical level inheritance
Here, classes Student, Software Engineer and Doctor are the child classes which are inheriting from
the parent class Person.
Figure 44:Code for Hierarchical level inheritance
Figure 45:Output
1.1.9.5 Multiple inheritance
If a class implements multiple interfaces or an interface extends multiple interfaces, it is known as
multiple inheritance. It means that multiple inheritance refers to the process where one child class tries
to extend more than one parent class. It is shown to derive a class from more than one class
simultaneously. This way the derived class will acquire the features of all of its parent classes. This may
give rise to serious ambiguities especially when the features inherited are the same.
More importantly, it is considered that in java, multiple inheritance is not supported in case of class
because of ambiguity. But it is supported in case of interface because there is no ambiguity as
implementation is provided by the implementation class.
Figure 46:Multiple Inheritance
The above image is illustrated that class Person inherits from interfaces moveable and speakable.
Figure 47:Code for Multiple inheritance
As it has explained in the above image, Moveable and Speakable interface have two methods but its
implementation is provided by class Person, so there is no ambiguity. So after implements keyword,
there can be any number of interfaces. In the following code, class Person implements two interfaces
Moveable and Speakable.
Figure 48:Code for Multiple inheritance
1.1.9.6 Hybrid Inheritance
Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance.
This type of inheritance can also achieve through the use of the interfaces.
Figure 49:Hybrid inheritance
The above image is represented that class Person is a parent class for classes Moveable and Speakable,
whereas classes Moveable and Speakable are the parent classes of Ablility which is the only child class
of Moveable and Speakable.
Figure 50:Code for Hybrid inheritance
Figure 51: Output
1.1.10 Polymorphism
Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means forms. It is the
ability of a variable, function or object to take on multiple forms. In other words, polymorphism allows
programmer to define one interface or method and have multiple implementations.
Polymorphism can divide into two type in java that are:
1.
Runtime polymorphism
2.
Compile time polymorphism
1.1.10.1. Runtime Polymorphism
In Java, runtime polymorphism refers to a process in which a call to an overridden method is resolved
at runtime rather than at compile-time. In other words, dynamic polymorphism can be achieved at run
time with the help of Method Overriding. Method Overriding is a feature that allows user to redefine
the method in the subclass or derived class which is already defined in its parent class or superclass. In
other words, a derived class or child class can provide a specific implementation of a function or method
that is already defined in one of its parent classes.
Method overriding is achieved that when a method of a derived or sub-class has the same name, same
return type and with the same arguments as a method in its parent class, then say that the method in the
superclass is being overridden by the method in the subclass.
This concept when a method of a subclass overrides the same method in its superclass, but with a
different implementation, is called Method Overriding.
Figure 52:Code for runtime polymorphism
Here have created two classes Parent and Child. The Child class inherits the Parent class. Both classes
have a common method void move(). The child class is giving its own implementation to the move()
method. In other words, it is overriding the move() method of the parent class. When calling this
overridden method, it will execute the method of the child class, not the parent class. The method
overriding represent the relationship of inheritance between them.
Figure 53:Output
1.1.10.2. The purpose for runtime polymorphism
Runtime polymorphism is also called as late binding or dynamic binding.
In Runtime polymorphism the linking between function call and function definition is done at run time
only.
1.1.10.3. Compile time Polymorphism
In Java, compile time polymorphism refers to a process in which a call to an overloaded method is
resolved at compile time rather than at run time. In other words, static polymorphism can be achieved
at compile time with the help of Method Overloading. Method overloading deals with two or more
methods with the same name, but with a difference in the method signatures is called method
overloading (Team, 2021). Method signature represents the method name along with the method
parameters. Method is called depending upon the difference in the method name. The difference may
be due to the following:
There is a difference in the number of parameters.
1.
void add (int a,int b)
2.
void add (int a,int b,int c)
There is a difference in the data types of parameters.
1.
void add (int a,float b)
2.
void add (double a,double b)
There is a difference in the sequence of parameters.
1.
void swap (int a,char b)
2.
void swap (char a,int b)
1.1.10.4. Important rules for method overloading
1. Two or more methods can have the same name inside the same class if they accept
different arguments. This feature is known as method overloading.
2. Method overloading is achieved by either changing the number of arguments or
changing the data type of arguments.
3. It is not method overloading if it only changes the return type of methods. It must be
differences in the number of parameters.
Method overloading is represented that method to execution based upon the type of the object being
referred to at the time the call occurs. Therefore, this determination is made at runtime. In this process,
an overridden method is called through the reference variable of a super class. The determination of the
method to be called is based on the object being referred to by the reference variable. Below image is
how method overload archives in compile time polymorphism.
Figure 55:Code for compile time polymorphism
Figure 54:Output
1.1.10.5. The purpose for compile time polymorphism
Compile time polymorphism is also called as early binding or static binding. In Compile tile
polymorphism the linking between function call and function definition is done at compile time only.
1.1.11Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship where one object
contains other objects as a part of its state. It represents the weak relationship between objects. It is also
termed as a “has a” relationship in Java. Like, inheritance represents the “is-a” relationship. It is
another way to reuse objects. An object will always be referenced with aggregation by other objects.
The relationship can be shown by an open diamond (a diamond without any fill color) in the UML.
Figure 56:Example of aggregation relationship in OOP
As image illustrate, a car can have multiple Passengers and one Driver within. Using the blank diamond,
it demonstrates that the lives of the Passengers and Drivers are not bound to the car.
Figure 57:Code for aggregation relationship
Figure 58:Output
The aggregation is exposed the maintenance of code reusability that it does not need to use the same
code again and again. Here is used the reference of Car class while defining each of these classes like:
Driver has-a Car (Has-a relationship between driver and car)
Passenger has-a Car (Has-a relationship between passenger and car)
1.1.12 Composition
The composition is also a way to achieve Association. The composition represents the relationship
where one object contains other objects as a part of its state. There is a strong relationship between the
containing object and the dependent object. It is the state where containing objects do not have an
independent existence. If you delete the parent object, all the child objects will be deleted automatically
UML uses a solid diamond symbol to denote composition.
Figure 59:Example of composition relationship in OOP
A car has got an engine. In other words, an engine is a part of car. Here, a car is a whole, and engine is
a part of that car. If the car is destroyed then its engine will be destroyed as well. So, without the
existence of car, there is no life of an engine. The life of an engine is totally dependent on the life cycle
of car.
Figure 60:Code for composition relationship in OOP
Figure 61:Output
Composition features
1.
It is a more restrictive form of aggregation.
2.
In composition, both the entities are associated with each other.
3.
Composition allows the changing of member objects at run time so that we can
dynamically change the behavior of our program
2. Task 02
2.1.Introduction to UML Diagram
UML short for Unified Modeling Language, is a graphical language for visualizing, specifying,
constructing, and documenting the artifacts of a software system. The UML offers a standard way to
write a system's blueprints, including conceptual things such as business processes and system functions
as well as concrete things such as programming language statements, database schemas, and reusable
software components.
The aim of UML is to provide a standard notation that can be used by all object-oriented methods and
to select and integrate the best elements of precursor notations. UML has been designed for a broad
range of applications. Hence, it provides constructs for a broad range of systems and activities such as
distributed systems, analysis, system design and deployment.
UML helps to create own set of diagrams to meet requirements. Diagrams are commonly made in an
incremental and iterative way.
2.1.1. Usage of UML Diagram
1. Bring new team members or developers switching teams up to speed quickly.
2. Navigate source code.
3. Plan out new features before any programming takes place.
4. Communicate with technical and non-technical audiences more easily.
There are 14 different types of UML diagrams, and they are divided into two categories:
1. Structural Diagrams
2. Behavioral Diagrams
Figure 62:UML Diagram types
2.2. Design and build the detailed UML class diagram for the Family Dental Care
system
Figure 63: Class diagram for FDC
In this FDC class diagram, each class is represented by a box with three sections stacked on top of each
other with class name, attributes and operations. In this diagram, each class has several attributes and
operations with different purpose. All classes represent symbol before the attribute and method name
indicate its visibility private (–) public (+). Here person class is single but staff, doctor and patient have
inherited person because they have the same attributes and operations so, it is called inheritance. The
inheritance relationship indicates in diagram by drawing an unfilled arrow from the person class to
doctor, staff and patient class.
The patient class indicate association relationship among appointment, payment, treatment, doctor.
Hence, generally patient has to take an appointment their doctor who can give consultation for them so
the relationship are book and consult respectively. Doctor class is inherited two types of doctor, one is
ordinary another consultant. Doctor class is connected to few classes such as FDC building, scan
machine, appointment and treatment. Therefore, receptionist and manager can schedule an appointment
to a doctor. Doctor can operate machine and provide treatment. That indicate the association
relationship as ‘operate’ and ‘provide’.
Staff are three types such as receptionist, manager and nurse. They have created as separate classes.
Receptionist class associated with payment class and appointment class. Those relationships indicated
as ‘receive payment’ and ‘handle appointment’. Manager class is connected nurse class to assign room,
scan machine class to assign dentist and surgery room class to allocate doctor & nurse.
Then, Aggregation and Composition are important relationships that are represented in FDC classes.
Association is contained Multiplicity that are indicated one to one, one to many and many to many
among classes. FDC building class contains room class and it’s life cycle is depended on the FDC
building class. Hence, it’s represented as a composition relationship. Room class is divided into two
types such as scan room and surgery room. Hence, it’s represented with the inheritance relationship.
As, Scan machine is kept in the scan room & both life cycle is independent, it was represented by the
aggregation relationship in the class diagram.
2.3.Inheritance
These classes are Person, Staff, and Doctor as shown in diagram. Further, for “Person” class is a
superclass to staff that include manager, nurse, receptionist and doctor which include ordinary dentist
and consultant. All of these, share a relationship and these relationships are known as inheritance
relationships.
2.4.Composition
The class is FDC building which share a relationship to room and its relationship is known as
composition because if the FDC building destroy, the room will destroy too.
Therefore, the composition represents strong.
2.5.Multiplicity
As shown in diagram, many patients are associated with many doctors for consulting denoted by and
this represents a many-to-many type of relationship. One patient has only one appointment that is
denoted by 1 and this represents a one-to-one type of relationship. Many nurses are associated with one
manager, and this represents many-toone or one-to-many type of relationship.
2.6.Developed Family Dental Care system for the scenario
Figure 64:Login Form
The Family Dental Care system has contained two user logins which are manager and receptionist.
Both has different access levels such as Manager can manage all type of data with all the options of
the system but delete option was disabled for the receptionist inorder to prevent the data deletion by
the receptionist. Hence receptionist has the accessibility to add, update and search data.
Figure 65:Validation for textbox
Figure 66:Validation message
Figure 67:Login for manager
Figure 68:Login for receptionist
Figure 69:Dashboard by manager
After login one of the user type, if manager is login, the dashboard will pop up on the screen and he
can manage or use all option. But if the login is been by receptionist, the dashboard will pop up with
restricted privileges respectively.
Figure 70:Dashboard by receptionist
Figure 71:Doctor Registration by manager
In doctor form, manager can register doctor with doctor id, doctor type, name, nic no, age, gender,
email, address, qualification, experience, county and contact no. but if doctor type is prominent the
textbox will be disabled for qualification and country otherwise will enabled respectively.
Figure 72:Doctor Registration by receptionist
Figure 73:Patient registration
In patient form, manager can register patient with patient id, first name, last name, nic no, gender, age,
blood group, address, and contact no. but if receptionist is login the form will be disabled the delete
button otherwise will be enabled respectively.
Figure 74:Appointment
In appointment form, manager can fill with single click on room details button to get room registration
details. As shown table, there is stored patient and doctor details.
Receptionist or manager can fill by clicking data.
Figure 75:Room allocation
In this form, Staff can register rooms by using room type such as scan room, surgery room 1, surgery
room 2, surgery room 3 and surgery room 4.
Figure 76: Staff registration
In staff form, manager can register staff with staff id, first name, last name, gender, age, email, address,
job type and contact no. But if receptionist is login, the form will be disabled the delete button otherwise
will be enabled respectively.
Figure 77:Add Code
Figure 78:Update Code
Figure 79: Delete Code
2.7.Object Oriented Concept used in Family Dental Care System
Abstract
Figure 80:Abstract class
Figure 81:Info table extends table class
Figure 82:Called abstract method
All the data of FDC stored in the database as separate tables. Hence, the process of accessing those data
from the database table should kept secure in FDC system. Here, abstraction is used for hiding table
information of all the tables in FDC system. FDC has got many data of patient and doctors. By using
abstraction, there implementation of accessing table data using query was hidden to access from other
classes. inforTableData was created as abstract method. The implementation for the method was given
within the child class.
Encapsulation
Figure 83:Class creation
Figure 84:Set values
Figure 85:Called getter methods
The Family Dental Care system have developed using oop concept encapsulation to secure the sensitive
data such as username & password. Encaptext class is created with private attributes to control and
restrict external access and provided with public getter and setter methods to indirectly access them.
Therefore, username and password will be kept from outside misuse and steal.
Polymorphism
Figure 86:Polymorphism code example
Here, the Infortable inherits table from table class.
Therefore, the infortable includes method
inforTableData. There is no need to create this method into the InforTable again. Hence there is possible
to override that method and provided varies implementation within class.
Inheritance
Figure 87:Inheritance code example
Here, the login class inherits JFrame class. The inherited class allows user to access properties and
methods. Therefore, this concept will prevent the code from being repeated.
3. Task 03
3.1.Determine and briefly discuss the range of design patterns
Design Patterns that are a well-described solution to a common software problem are very popular
among software developers. Java Design Patterns are divided into three categories – creational,
structural, and behavioral design patterns. (Pankaj, 2022) A design pattern is a language independent
strategy for solving common object oriented design problem. It describes how to structure classes to
meet a given requirement. Design patterns are practical solutions to general problems that software
engineers faced during software development. All these patterns are like blueprints that can use and
customize to solve those specific problems in code.
The credit of Design Patterns goes to the Gang of Four. Erich Gamma, Richard Helm,
Ralph Johnson and John Vlissides were the authors of the book on the Java Design Patterns.
3.1.1 Gang of four (GoF)
In 1994, 4 authors known as “Gang of Four” released a book named as “Design Patterns”. In that book
they divided all these design patterns into three categories. At the moment there are 23 design patterns
and all these are categorized under these 3 types of categories named as, Creational, Structural, and
Behavioral.
Figure 88:Design pattern categorize
3.1.2 Structure of a Design Pattern
Structure of any Design Pattern is considered to be highly organized. They are often documented in
the form of a template such that, the users can visually identify the problem and instantaneously find
the solution to it, based on the relationship between classes and objects. Each pattern is divided into
sections according to the following table. The table describe a uniform structure to the information,
making design patterns easier to learn, compare, and use as follows:
Term
Description
Pattern Name
Describes the essence of the pattern in a short, but expressive name.
Intent
Describes what the Pattern Does
Also, known as
List any synonyms of the pattern
Motivation
Provides an example of the problem and describes the solution to it
Applicability
Lists the situations where the pattern is applicable
Structure
Set of diagrams of the classes and objects that depict the pattern
Participants
Describes the classes and objects that participate in the design
Collaborations Describes the Participants collaboration and their responsibilities. Consequences
Describes the forces that exist with the pattern and the benefits
Table 1 Design pattern structure description
Generally, following are the steps to follow to create a design pattern Name: Important as a part of
the design vocabulary. Problem: When to apply the pattern.
Solution: Design elements, along with their relationships, responsibilities and collaborations.
Main Usage of Design Pattern
Design Patterns have two main usages in the field of software development.
Common platform for developers: Design patterns provide a standard terminology and are specific
to particular scenario. For example, a singleton design pattern signifies use of single object so all
developers familiar with single design pattern will make use of single object and they can tell each
other that program is following a singleton pattern. Best Practices: Design patterns have been
evolved over a long period of time and they provide best solutions to certain problems faced during
software development. Learning these patterns helps unexperienced developers to learn software
design in an easy and faster way.
3.1.3 Category of GOF design pattern and their purpose
1. Creational Patterns
1. Abstract Factory: Provide an interface for creating families of related or dependent
objects without specifying their concrete classes.
2. Singleton: Ensure a class has only one instance, and provide a point of access to it 3.
Builder pattern which constructs complex objects by separating construction and
representation.
3. Factory method pattern that creates objects without specifying the exact class to
create.
4. Prototype pattern which creates objects by cloning an existing object.
2. Structural Patterns
1. Adapter that allows classes with incompatible interfaces to work together by wrapping
its own interface around that of an already existing class.
2. Bridge which decouples an abstraction from its implementation so that the two can
vary independently.
3. Composite: Compose objects into three objects to represent part-whole hierarchies.
Composite lets clients treat individual objects and compositions of objects uniformly.
4. Decorator that dynamically adds or overrides behavior in an existing method of an
object.
5. Facade provides a simplified interface to a large body of code.
6. Flyweight which reduces the cost of creating and manipulating a large number of
similar objects.
7. Proxy provides a placeholder for another object to control access, reduce cost, and
reduce complexity.
3. Behavioral Patterns
1. Chain of responsibility: delegates commands to a chain of processing objects.
2. Command: creates objects which encapsulate actions and parameters.
3. Interpreter: implements a specialized language.
4. Iterator: Defines an interface for accessing and traversing elements of a collection at
sequentially
5. Mediator: allows loose coupling between classes by being the only class that has
detailed knowledge of their methods.
6. Memento: provides the ability to restore an object to its previous state (undo).
7. Observer: Define a one-to-many dependency between objects so that when one object
changes state, all its dependents are notified and updated automatically.
8. State: allows an object to alter its behavior when its internal state changes.
9. Strategy: allows one of a family of algorithms to be selected on-the-fly at runtime.
10. Template method: defines the skeleton of an algorithm as an abstract class, allowing
its subclasses to provide concrete behavior.
11. Visitor: separates an algorithm from an object structure by moving the hierarchy of
equal methods into one object.
Advantage of using design patterns
1. Design patterns enable large scale reuse of software architectures and also help
document systems
2. Patterns explicitly capture expert knowledge and design trade-offs and make it more
widely available
3. Patterns help improve developer communication
Disadvantage of using design patterns
1. Patterns do not lead to direct code reuse
2. Integrating patterns into a software development process is a human intensive activity.
3.1.4 Creational Design Patterns
Creational patterns provide object creation mechanisms that can create objects in a controlled manner
that are suitable to the situation. In this way, they help reduce complexities and instability, while also
offering increased flexibility and allowing for the reuse of code. Key pattern examples include
Singleton, Factory Method, Abstract Factory, Prototype, and Builder.
Figure 89:Creational design patterns
Mainly, Creational design patterns are concerned with the way of creating or instantiating objects.
These patterns can be further categorized into:
1. Class creational patterns
2. Object creational patterns.
While class creation patterns use inheritance effectively in the instantiation process, object creation
patterns use delegation effectively to get the job done.
Figure 90:UML Diagram of creation design patter
1. Singleton
Singleton is one of the Gangs of Four Design patterns and comes in the Creational Design Pattern
category.
A singleton which seems to be a very simple design pattern but when it comes to
implementation, comes with a lot of implementation concerns. The implementation of Singleton pattern
has always been a controversial topic among developers.
Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class
exists in the java virtual machine. The singleton class must provide a global access point to get the
instance of the class. Singleton pattern is used for logging, driver objects, caching and thread pool.
Singleton design pattern is used in core java classes also, like java.lang.Runtime, java.awt.Desktop.
To implement Singleton pattern that have different approaches but all of them have following common
concepts.
1.
Declare the constructor as Protected
2.
Declare a static "self" pointer to hold a reference to the single instance when it is created
3.
Declare a static "instance" function which creates and returns the single instance if the selfpointer is NULL, otherwise it just returns the previously created instance.
4.
Declare a protected destructor that sets the "self" pointer to NULL
5.
Declare other methods and attributes as needed normally.
Consider when implementing singleton
1.
There must be exactly one instance of a class, and it must be accessible to clients from a well-
known access point.
2.
When the sole instance should be extensible by sub classing, and clients should be able to use
an extended instance without modifying their code.
UML Diagram of singleton pattern
It is going to create a SingleObject class. SingleObject class have its constructor as private and have a
static instance of itself. SingleObject class provides a static method to get its static instance to outside
world.SingletonPatternDemo, the demo class will use SingleObject class to get a SingleObject object.
Figure 91:UML diagram of singleton pattern
The implementation code follows the steps of above diagram pattern.
Implementation code
Step 1: Create a Singleton Class by declaring SingleObject.java
Figure 92:SingleObject.java
Step 2: Get the only object from the singleton class
Figure 93:SingletonPatternDemo.java
Step 3: Verify the output
Figure 94:Output
Singleton objects can be created in two ways.
1.
Early Instantiation: creation of instance at load time.
2.
Lazy Instantiation: creation of instance when required
Eager Instantiation: In the eager instantiation variant of the Singleton pattern, a singleton instance is
created and assigned to a static attribute in an initialization block. Initialization blocks are usually
executed at the beginning of a program or when the class is loaded. Thus, it may happen that the
singleton instance is constructed even if it is not accessed. This is a drawback, especially when the
construction involves allocation of limited resources. The advantage of this variant is its simplicity and
(usually) thread safety (often a language guarantees the thread safe execution of static initialization
blocks).
The implementation of static initialization singleton class.
Figure 95:Eager Initialized Singleton
Lazy Instantiation: The most popular variant of the Singleton implementation involves the lazy
instantiation of a singleton instance. An access method checks whether the instance is constructed, and
if not, it creates one. This variant avoids the drawback of eager instantiation, as no resources are
allocated before the instance is actually accessed. However, this variant must be used carefully in a
multi-threaded environment. Without additional synchronization, it may happen that the singleton
constructor is called several times, resulting in undesired side effects and resource consumption.
Figure 96:Lazy Initialized Singleton
Advantages of using singleton
1. As only one instance of the singleton class is used, we save memory.
2. Also, ensures reusability as the same singleton object is used again and again.
3. Singleton can be extended to work across many computers.
4. You can change any class into a singleton simply by making its constructors private and by
adding the appropriate static functions and variable.
5. Can be created through derivation. Given a class, you can create a subclass that is a
singleton.
Disadvantage of using singleton
1. Creates tightly coupled code that is difficult to test. Makes it almost impossible to subclass Singleton.
2.Factory design pattern
A Factory Pattern says that just define an interface or abstract class for creating an object but let the
subclasses decide which class to instantiate. In other words, subclasses are responsible to create the
instance of the class. The Factory Method Pattern is also known as Virtual Constructor.
UML Diagram of Factory Pattern
It is going to create a Shape interface and concrete classes implementing the Shape interface. A factory
class Shape Factory is defined as a next step. Factory Pattern Demo, the demo class will use Shape
Factory to get a Shape object. It will pass information CIRCLE, RECTANGLE, SQUARE to Shape
Factory to get the type of object it needs.
Figure 97:Example UML diagram of factory pattern Implementation
Step 1: Create an interface for Shape.java
Figure 98:Shape.java
Step 2: Create concrete classes implementing the same interface for Rectangle.java
Figure 99:Rectangle.java
Create concrete classes implementing the same interface for Square.java
Figure 100:Square.java
Create concrete classes implementing the same interface for Circle.java
Figure 101:Circle.java
Step 3: Create a Factory for ShapeFactory.java to generate object of concrete class based on given
information
Figure 102:ShapeFactory.java
Step 4: Use the Factory to get object of concrete class by passing an information such as type
FactoryPatternDemo.java
Figure 103:FactoryPatternDemo.java
Step 5: Verify the output
Figure 104:Output
Advantage of Factory pattern
1.
It can move the product creation code into one place
2.
Factory design pattern provides approach to code for interface rather than implementation.
3.
Factory pattern removes the instantiation of actual implementation classes from client code.
4.
Factory pattern makes code more robust, less coupled and easy to extend.
5.
Factory pattern provides abstraction between implementation and client classes through
inheritance.
Disadvantage of Factory pattern
1. The code may become overly complicated because of all the subclasses within the pattern
3.Abstract Factory Pattern
Abstract Factory patterns that work around a super-factory which creates other factories is also called
as factory of factories. This type of design pattern comes under creational pattern as this pattern provides
one of the best ways to create an object. In Abstract Factory pattern an interface is responsible for
creating a factory of related objects without explicitly specifying their classes. Each generated factory
can give the objects as per the Factory pattern.
UML Diagram of Abstract Factory Pattern
It is going to create a Shape and Color interfaces and concrete classes implementing these interfaces.
We create an abstract factory class Abstract Factory as next step. Factory classes Shape Factory and
Color Factory are defined where each factory extends Abstract Factory. A factory creator or generator
class Factory Producer is created. Abstract Factory Pattern Demo, the demo class uses Factory Producer
to get an Abstract Factory object. It will pass information CIRCLE, RECTANGLE, SQUARE for
Shape to Abstract Factory to get the type of object it needs. It also passes information RED, GREEN,
BLUE for Color to Abstract Factory to get the type of object it needs.
Figure 105:Example UML diagram of abstract factory pattern
Implementation code
Step 1: Create an interface for Shapes. Shape.java
Figure 106:Shape.java
Step 2: Create concrete class for Rectangle.java implementing the same interface.
Figure 107:Rectangle.java
Create concrete class for Square.java implementing the same interface.
Figure 108:Square.java
Create concrete class for Circle.java implementing the same interface
Figure 109:Circle.java
Step 3: Create an interface for Colors. Color.java
Figure 110:Color.java
Step 4: Create concrete class for Red.java to implement the same interface.
Figure 111:Red.java
Create concrete class for Green.java to implement the same interface.
Figure 112:Green.java
Create concrete class for Blue.java to implement the same interface
Figure 113:Blue.java
Step 5: Create an Abstract class to get factories for Color and Shape Objects.
Figure 114:AbstractFactory.java
Step 6: Create Factory classes extending AbstractFactory to generate object of concrete class based on
given information
Figure 115:ShapeFactory.java
Figure 116:ColorFactory.java
Step 7: Create a Factory generator or producer class to get factories by passing an information such as
Shape or Color
Figure 117:FactoryProducer.java
Step 8: Use the FactoryProducer to get AbstractFactory in order to get factories of concrete classes by
passing an information such as type AbstractFactoryPatternDemo.java
Figure 118:AbstractFactoryPatternDemo.java
Step 9: Verify the output
Figure 119:Output
4. Prototype Pattern
Prototypes design pattern allows you to create objects by cloning an existing object instead of creating
a new object from scratch. This pattern is used when the process of object creation is costly. When
cloning, the newly copied object contains the same characteristics as its source object. After cloning,
we can change the values of the new object’s properties as required. This pattern comes under a
creational pattern.
Implementation prototype pattern
Step 1: Create an Employee class
Figure 120:Employee.java
Figure 124 Department.java
Figure 125 Test.java
Figure 121: Output
Consider when creating prototype
1. The class of the object we are trying to clone or its one of parent class must implement
Runnable Interface, else it will throw CloneNotSupportedException.
2. The class which implements Runnable Interface should override clone() method. the
body of the clone() method should contain return super.clone() .
3. There should be a registry class that contains one object of each source object. The
Register class must contain a method that will clone a new object from the source
object and return that new object.
Advantage of Prototype Pattern
1. By cloning, it cut down the resource consumption of object creation.
2. Clients can get new objects, without knowing which type it belongs to.
3. It allows you to add or remove objects at runtime.
4. It reduces the need for sub-classing.
3.1.5 Structural Design Patterns
Structural patterns which are concerned with how classes and objects are composed to form larger
structures, are particularly useful for making independently developed class libraries work together.
Structural class patterns use inheritance to compose interfaces or implementations. As a simple
example, consider how multiple inheritance mixes two or more classes into one. The result is a class
that combines the properties of its parent classes.
Rather than composing interfaces or implementations, structural object patterns describe ways to
compose objects to realize new functionality. The added flexibility of object composition comes from
the ability to change the composition at run-time, which is impossible with static class composition.
1. Composite Pattern
Composite pattern is one of the Structural design pattern. The Composite design pattern is a partitioning
design pattern and describes a group of objects that are treated the same way as a single instance of the
same type of object. The intent of a composite is to “compose” objects into tree structures to represent
part whole hierarchies. It allows user to have a tree structure and ask each node in the tree structure to
perform a task. The concept is that user can manipulate a single instance of the object just as they would
manipulate a group of them. The operations user can perform on all the composite objects often have
the least common denominator relationship.
The Composite Pattern has four participants:
Client: The Client manipulates the objects in the composition through the component interface. It is
only aware of Leaf’s and Composites through the Component Interface. Component: Component
declares the interface for objects in the composition and for accessing and managing its child
components. It also implements default behavior for the interface common to all classes as appropriate.
Leaf: Leaf defines behavior for primitive objects in the composition. It represents leaf objects in the
composition.
Composite: A Component that can contain other components. It stores child components and
implements child-related operations in the component interface.
UML Diagram of Composite pattern
Here have a class Family which acts as composite pattern actor class.
CompositePatternDemo, the demo class will use Family class to add parent child level hierarchy and
print all families.
Figure 122:UML diagram for composite pattern
Consider few things when implementing:
1. Essential to maintain the invariant that all children of a composite have as their parent the composite
that in turn has them as children
2. Easiest way to ensure 1 change the component's parent only 2 when it is being added or removed from
composite
Implementation code
Step 1: Create Family class having list of Family objects.
Figure 123:Family.java
Step 2: Use the Family class to create and print family hierarchy.
Figure 124:CompositePatternFamily.java
Step 3: Verify the output.
Figure 125:Output
Advantage of Composite pattern
1. Simplification of execution: Clients can treat composite structures and individual
objects uniformly. Clients normally don’t know (and shouldn’t care) whether they’re
dealing with a leaf or a composite component. This simplifies client code, because it
avoids having to write a case statement in the functions over the classes that define the
composition.
2. Easy to add new kinds of components: Newly defined Composite or Leaf subclasses
work automatically with existing structures and client code. Clients don’t have to be
changed for new Component classes.
Disadvantage of Composite pattern
1. General Design: The disadvantage of making it easy to add new components is that
it makes it harder to restrict the components of a composite. Sometimes you want a
composite to have only certain components. With Composite, you cannot rely on the
type system to enforce those constraints for you. You will have to use run-time checks
instead.
2. Restriction on primitives is a very unusual form of applying inheritance
3.1.6 Behavioral Patterns
Behavioral patterns that describe not just patterns of objects or classes but also the patterns of
communication between them, are concerned with algorithms and the assignment of responsibilities
between objects. These patterns characterize complex control flow that is difficult to follow at run time.
They shift the focus away from flow of control to let the concentrate just on the way objects are
interconnected.
Behavioral object patterns use object composition rather than inheritance. Some describe how a group
of peer objects cooperate to perform a task that no single object can carry out by itself.
An important issue here is how peer objects know about each other. Peers could maintain explicit
references to each other, but that would increase their coupling. In the extreme, every object would
know about every other.
1. Iterator Pattern
According to GoF definition, an iterator pattern provides a way to access the elements of an aggregate
object sequentially without exposing its underlying representation. Iterator helps in traversing the
collection of objects in a defined manner which is useful the client applications. During iteration, client
programs can perform various other operations on the elements as per requirements.
The iterator pattern allows to access elements of a collection without exposing the internal structure of
elements or collection itself and supports multiple simultaneous traversals of a collection from start to
end in forward, backward or both directions. Iterator provide a uniform interface for traversing different
collection types transparently. The main idea is that Abstract the traversal of different data structures
so that algorithms can interface with each transparently.
1.
Iterator: Defines interface for accessing and traversing elements
2.
Concrete Iterator: Implements the Iterator interface. Keeps track of current
position in traversal
3.
Aggregate: Defines interface for creating an Iterator object
4.
Concrete Aggregate: Implements the Iterator creation interface to return an
instance of its associated Concrete Iterator
Consider iterator pattern when implementing
1.
In order to encapsulate the iteration over the data structures, we need to abstract two jobs
2.
Determine if we need to keep iterating and get the next item
3.
Create Iterator interface with these methods
4.
hasNext() (return boolean) and next() (return Object)
5.
Since next() returns an Object, we’ll have to cast retrieved objects
6.
Create two implementations of the Iterator interface, one for each menu
7.
Update menu classes to return an iterator
8.
Update client code (Waitress) to retrieve iterators and loop over them
UML Diagram for iterator design pattern
Figure 126:UML Diagram of iterator pattern
Benefits of iterator pattern
1.
Access an aggregate object’s contents without exposing its internal representation
2.
Support multiple traversals of aggregate’s objects
3.
Provide a uniform interface for traversing different aggregate structures
Implementation code
Step 1: the class has created with interface. It has two methods that have Next and next. has Next which
is represented, returns true if the iteration has more elements. Next that is represented, returns the next
element in the iteration.
Figure 127:Iterator.java
Step 2: this class has also created with interface, but it has one method that is get Iterator. get Iterator
which returns an implementation of Iterator interface for traversal over, is represent.
Figure 128:Iterable.java
Step 3: The Product Catalog class contains a sting array storing product names will implement Inerrable
interface to provide an iterator object to traverse product catalog. The Product Catalog class contains
an inner class Product Iterator which implements Iterator interface for the traversal of product catalog.
Product Iterator class contains the logic regarding how to traverse product catalog, which is hidden from
the client.
Figure 129:ProductCatalog.java
Step 4: Use the IteratorPatternExample to get iterator and print product names.
Figure 130:IteratorPatternExample.java
Step 5: verify the output
Figure 131:Output of iterator
2. Observer 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 automatically. In observer pattern, there are many
observers (subscriber objects) that are observing a particular subject (publisher object). Observers
register themselves to a subject to get a notification when there is a change made inside that subject. An
observer object can register or unregister from subject at any point of time. It helps is making the objects
loosely coupled.
1.
Subject: It is considered as the keeper of information, of data or of business logic.
2.
Register or Attach: Observers register themselves to the subject because they want to be
notified when there is a change.
3.
Event: Events act as a trigger in the subject such that all the observers are notified.
4.
Notify: Depending on the implementation, the subject may “push” information to the observers,
or, the observers may “pull” if they need information from the subject.
5.
Update: Observers update their state independently from other observers however their state
might change depending on the triggered event.
UML Diagram for observer pattern
Figure 132:UML diagram of observer pattern
Implementation code
Step 1: Create Subject class.
Figure 133:Subject.java
Step 2: Create observer class.
Figure 134:Observer.java
Step 3: Create concrete observer classes.
Figure 135:Rectangle1.java
Figure 136:Rectangle2.java
Step 4: Use Subject and concrete observer objects.
Figure 137:ObserverPatternRectangle.java
Step 5: verify the output.
Figure 138:Output
3.2. Analyze the relationship between object-oriented paradigm and design patterns
A large number of design patterns involve Object Oriented Programming. A design pattern is a
commonly used approach to program creation and is to solving problems that come up on OOP
programming. OOP is a specific conceptual paradigm, which some programming patterns fit into it.
Design pattern is a description of communicating objects and classes that are customized to solve a
general design problem in a particular context. The relationship is that the standard response to both
design patterns and OOP often points to working with a team of programmers and speaking the same
language. In addition to coordinating large projects, programmers use both OOP and design patterns to
deal with change. One key, important element, of design patterns is that they make changing a program
much easier.
In design pattern, the union design pattern is a structural pattern that depicts the inheritance relationship
between a superclass and its subclasses. The delegation design pattern is in OOP where an object,
instead of performing one of its stated tasks, delegates that task to an associated helper object. Using
normal OOP techniques in design pattern, one would make an interface or virtual methods that each
class implements. Factory method is a creational pattern that helps create an object without the user
getting exposed to creational logic.
Therefore, design patterns and good OOP ease the task of making changes in complex programs, and
reduce the changes or global problems.
Example of scenario using design pattern in object-oriented concept
In object-oriented programming, a Composite is an object designed as a composition of oneor-more
similar objects as employee’s hierarchy scenario. It represents all exhibiting similar functionality. This
is known as a “has-a” relationship between objects.
4.Task 04
4.1 Scenario 1
The singleton pattern is a software design pattern that restricts the instantiation of a class to one "single"
instance. This is useful when exactly one object is needed to coordinate actions across the system.
4.1.1.
Choose design pattern for scenario 1
Based on the scenario, there mentioned FDC owns a very expensive, state of the art dental scan machine
and that device is far superior to a traditional dental X-ray machine manufactured by Toshiba, Japan.
FDC will be owning just one such machine in the foreseeable future. At the same time, they requested
when modeling and implementing the FDC system in software, it has been ensured that only one
instance can create for scan machine.
There are analyzed among the different type of design pattern in java. When analyzing the design pattern
for scenario 1, there was one as matched which has singleton design pattern. The Singleton pattern
ensures that a class has only one instance and provides a global point of access to that instance. It is
named after the singleton set, which is defined to be a set containing one element. Scan machine of
FDC is a Singleton. The FDC owner specifies one object creation which is limited in creating number
of machines in system. Hence, the idea of having a singleton pattern is to control one instance. As it
makes the constructor private, it cannot create another object as a new. Therefore, it can control the
creation of new instance using singleton design pattern.
4.1.2.
Comparison among design patterns
After researching among the design patterns, the composite pattern describes a group of objects. The
intent of a composite is to "compose" objects into tree structures to represent part whole hierarchies.
Hence, this design pattern is inappropriate to the scenario 1. Then, as the iterator pattern is used to
traverse a container and access the container's elements, it is not suitable for it. Another one is Observer
pattern which defines a one-to-many dependency between objects so that when one object changes
state, all its dependents are notified and updated automatically. Hence, it also can’t use to create only
one instance. Therefore, all other patterns will not be suitable for first scenario. Based on the case
analyzing and evaluation on the patterns. Here the design pattern has been chosen singleton pattern for
the first scenario as suitable one. Hence, singleton pattern restricts the instantiation of a class to one
"single" instance. This is when exactly one object is needed to coordinate actions across the system as
same as they required.
Figure 139:Class diagram
The diagram has drawn using two classes which is Diver Scan Machine and Dental Scan Machine.
Driver Scan Machine class includes main method. Dental Scan Machine has attributes, methods and
constructor. Attributes are serial number, make, country and cost. Methods are display Scan Machine
Details and it is created create Scan Machine method using Dental Scan Machine class. Constructor is
Dental Scan Machine () which is to initialize the attribute values. The purpose of display method
creation is to display all the attribute values of Dental Scan Machine. Then create Scan Machine()
method defined to facilitate the only one object creation. If there is another object of Dental Scan
Machine is created, it will result an error as ‘scan machine is already created scan machine so you
cannot create it again.
Implementation code
Figure 140:Fist class creation
Figure 141:Continue
Figure 142:Main class
As per the scenario was given task, the dental X-ray scan machine should be created once. As the
creation has to be one, the code was implemented with the singleton design pattern. The scan machine
is created with attribute such as serial number, make, country and cost. Further, the create Scan Machine
method implemented to avoid the creation of multiple instances for the Dental Scan Machine class.
Figure 143:Output of scan machine creation
4.2 Scenario 2
Composite pattern is design pattern that describes a group of objects which is treated the same way as
a single instance of the same type of object. The intent of a composite is to “compose” objects into
tree structures to represent part whole hierarchies.
4.2.1 Choose design pattern for second scenario
According to the scenario required, Family Dental Care Hospital has got many staff working in FDC
includes the Director, Doctors and Nurses. The Director is seemed as the CEO of the FDC. Nurses are
working under the dentist. The system creates objects based on the structure of tree to represent the
whole hierarchy. With the result, Madhavi was assigned to work under the director, chamod was
assigned to work under supuni dentist and nurses were assigned to work under each dentist to work.
Furthermore, the id, name, position, and salary of the employees were given while they were working.
There were different types of design patterns which are analyzed in Java. When analyzing them, one
was suitable to implement the design that was known as composite design pattern. Composite Pattern
is a design solution in Java. As Composite Design patterns describe groups of objects, it can implement
in the same way as a family tree hierarchy.
Hence, Composite design pattern is more relevant to the scenario of employee hierarchy.
4.2.2 Comparison among the design patterns
After researching among the design patterns, the iterator pattern is used to traverse a container and
access the container's elements. So, it is not suitable for it. Then Observer pattern which defines a oneto-many dependency between objects so that when one object changes state, all its dependents are
notified and updated automatically. Therefore, it cannot create to hierarchy order of employees.
Singleton pattern restricts the instantiation of a class to one "single" instance. As this is when exactly
one object is needed to coordinate actions across the system, it cannot be at hierarchy order.
Therefore, not all patterns will be suitable for fist second scenario. Based on the case analyzing and
evaluation on the patterns. Here the design pattern has been chosen composite pattern for the second
scenario as suitable one. Hence, the composite pattern describes a group of objects. The intent of a
composite is to "compose" objects into tree structures to represent part whole hierarchies related to the
scenario 2.
Figure 144:Class diagram of Employees
FDC have got two class that is Composite Pattern FDC class and Employees class. The class Composit
Pattern FDC class contains the main method. The class Employees class has attribute, method and
constructor. Attribute are empId, name, Position, Salary, and subordinates. The methods are add,
remove, getSuboardinates and toString. The constructor is Employees () used to initialize the attributes
values. Add method works to add one employee under other employees according to the hierarchy given
in the scenario. Remove method works to remove employees. Getsuboardinate method works to store
employee into array format. Tostring method is to print all the details. It represents association
relationship between classes.
Implementation code
Figure 145:Employees.java
Figure 146:CompositePatternFDC.java
Figure 147:Continue
Figure 148:Output of employee’s hierarchy
4.3 Scenario 3
The iterator pattern is a design pattern in which an iterator is used to traverse a container and access
the container's elements.
4.3.1. Choose design pattern for third scenario
Based on the scenario, Patients who need dental scans are kept in a First in First out (FIFO) queue. They
requested to assume that we have found an already developed queue container in a software library. It
provides standard queue operations to insert and remove data (known as enqueue and dequeue
respectively). However, they need some specific operations such as search () to lookup a particular
patient and showAll() to list all the patients in the queue. These additional operations are not provided
by the library unit. A queue is an abstract data structure in this way. The queue is open at both its ends.
One is always used to insert data (enqueue) from end and the other is used to remove data (dequeue).
Queue follows First in First Out methodology that the data item stored first, will be accessed first.
As same as FDC is having their patient details in a container and get those with the queue data structure
(like an array).Since enqueue, dequeue functions available need to add additional functions such as
search () and showAll() to list of the patients in the queue and to search a patient details who are in the
queue.
Among the design, Iterator Design Pattern is suitable design pattern for the scenario. Iterator Pattern is
a relatively simple and often used among them. Many data collections are available in each language.
Each collection have to provide an iterator which allows it to accept its objects. In doing so, it has to
ensure that it does not expose its implementation. Hence, Iterator design Pattern is related pattern to the
scenario.
Figure 149:Class diagram of third scenario
The diagram has drawn using two interface and three classes. Interface are iterator and iteratable.
Iterator has got two methods hasNext() and next(). hasNext returns true if the iteration has more
elements. next() returns the next element in the iteration. Iteratable has got getIteratable method which
returns an implementation of Iterator interface for traversal over. PatientIterator inherit iterator to assess
its methods. PatienDetails has got attribute and methods. Attribute is patientDetails and methods are
search() and showAll(). Search() method uses for searching patient details showAll() method uses to
print patient details of FDC.
PatientDetails also inherit Iteratable interface. The main class is
IteratorFamilyDentalCare.
References
Hartman, J., 2022. What is Abstraction in OOPs?. [Online]
Available at: https://www.guru99.com/java-data-abstraction.html
[Accessed 27 July 2022].
Help, S. T., 2022. Java Class Vs Object – How To Use Class And Object In Java. [Online]
Available at: https://www.softwaretestinghelp.com/java-class-vs-object/ [Accessed 22 July 2022].
Lewis, A. S. G. &. S., 2022. Techtarget. [Online]
Available at:
https://www.techtarget.com/searchapparchitecture/definition/objectoriented-
programming-OOP [Accessed 29 06 2022].
Logic, S., 2022. What is
Encapsulation?. [Online]
Available at: https://www.sumologic.com/glossary/encapsulation/
[Accessed 27 July 2022].
Pankaj, 2022. Java Design Patterns – Example Tutorial.
Available at:
[Online]
https://www.journaldev.com/1827/java-design-patterns-example-tutorial [Accessed
27 July 2022].
Point, T., 2022. UML Available at:
Standard Diagrams. [Online]
https://www.tutorialspoint.com/uml/uml_standard_diagrams.htm [Accessed 27 July
2022].
Programming, J., 2021. Methods and dividing the program into smaller parts. [Online]
Available at: https://java-programming.mooc.fi/part-2/4-methods
[Accessed 27 July 2022].
Rabelo, J., 2021. What Does Java Object Mean?. [Online]
Available at:
https://www.techopedia.com/definition/24339/java-object#:~:text=A
%20Java%20object%20is%20a,are%20also%20known%20as%20classes.
[Accessed 26 July 2022].
Singh, C., 2022. Types of inheritance in Java: Single,Multiple,Multilevel & Hybrid.
[Online]
Available at: https://beginnersbook.com/2013/05/java-inheritance-types/ [Accessed 26 July 2022].
Singh, H., 2022. Inheritance in Object Oriented Programming for Python – An In-Depth Guide
for Everyone. [Online]
Available at: https://www.analyticsvidhya.com/blog/2020/10/inheritance-objectorientedprogramming/
Download