-
Notifications
You must be signed in to change notification settings - Fork 2
/
FactoryCodingExercise.java
51 lines (43 loc) · 1.2 KB
/
FactoryCodingExercise.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
Factory section exercise: given a class Person with two fields, id and name,
implement a non-static PersonFactory that has a createPerson() that takes a person's name
and returns a new instance of Person. The id returned is set on a 0-based index
*/
package creational.factories;
class Person
{
public int id;
public String name;
public Person(int id, String name)
{
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
class PersonFactory
{
private static int idCount = 0; // index-based counter for people
public static Person createPerson(String name)
{
Person p = new Person(idCount, name);
idCount++;
return p;
}
}
class FactoryCodingExercise {
public static void main(String[] args) {
Person first = PersonFactory.createPerson("Igor");
Person second = PersonFactory.createPerson("Lauren");
Person third = PersonFactory.createPerson("Opus");
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
}