-
Notifications
You must be signed in to change notification settings - Fork 1
/
abstractFactory.java
113 lines (95 loc) · 2.78 KB
/
abstractFactory.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
interface UserTable {
void add(String username, int age);
boolean find(String username);
}
interface Database {
UserTable createUserTable();
}
class MariaDB implements Database{
MariaDB(){
System.out.println("Welcome to using MariaDB database!");
}
@Override
public UserTable createUserTable() {
return new MariaDBUserTable();
}
}
class Oracle implements Database{
Oracle(){
System.out.println("Welcome to using Oracle database!");
}
@Override
public UserTable createUserTable() {
return new OracleUserTable();
}
}
class User {
User(String name, int age){
this.name = name;
this.age = age;
}
private String name;
private int age;
public String getName() {
return name;
}
}
class OracleUserTable implements UserTable {
// using List to implement table in database
List<User> list = new ArrayList<>();
@Override
public void add(String username, int age) {
list.add(new User(username, age));
}
@Override
public boolean find(String username) {
for (User u : list) {
if (u.getName().equals(username))
return true;
}
return false;
}
}
class MariaDBUserTable implements UserTable {
// using List to implement table in database
List<User> list = new ArrayList<>();
@Override
public void add(String username, int age) {
list.add(new User(username, age));
}
@Override
public boolean find(String username) {
for (User u : list) {
if (u.getName().equals(username))
return true;
}
return false;
}
}
public class Main {
public static void main(String[] args){
// Database db = new MariaDB();
// we can simply change MariaDB to Oracle without changing other client code
Database db = new Oracle();
UserTable userUserTable = db.createUserTable();
userUserTable.add("Yik Ming", 20);
userUserTable.add("Sing Lek", 20);
userUserTable.add("Jason Lee", 20);
userUserTable.add("Ting Ye", 20);
//input a username and query to database to check whether the user exists or not
Scanner console = new Scanner(System.in);
System.out.println("Please enter a username to find:");
do {
String username = console.nextLine();
if(userUserTable.find(username)){
System.out.printf("%s was found!\n", username);
} else {
System.out.printf("%s was not found!\n", username);
}
System.out.println("Please enter a username to find:");
} while(console.hasNextLine());
}
}