Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.util.Arrays;
import java.util.List;
/**
* 検索クラス
*/
public class Search {
private static List<Person> persons = Arrays.asList(
new Person("Tarou", "Tokyo"),
new Person("Jirou", "Osaka"),
new Person("Saburou", "Nagoya"));
static Person find(String name) {
for (Person p : Search.persons) {
if (p.getName().equals(name)) {
return p;
}
}
return new NullPerson(name); // null の代わりに Null オブジェクトを返す
}
public static void main(String[] args) {
System.out.println(find("Tarou").getAddress());
System.out.println(find("Hanako").getAddress());
}
}
/**
* 「人」を表わすクラス
*/
class Person {
private String name;
private String address;
Person() {
}
Person(String name, String address) {
this.name = name;
this.address = address;
}
String getName() {
return this.name;
}
String getAddress() {
return this.address;
}
@Override
public String toString() {
return this.name + ":" + this.address;
}
}
/**
* Null オブジェクト
*/
class NullPerson extends Person {
NullPerson(String name) {
super(name, "");
}
@Override
String getAddress() {
return super.getName() + " ha imasen";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment