搜尋此網誌

2012年4月2日 星期一

Design pattern - Java creation method


public class CreationMethod {

public static void main(String [] args){
Student s1 = Student.createInstance(1);
Student s2 = Student.createInstance(1, "hello");
System.out.println(s1.toString());
System.out.println(s2.toString());
}
}

class Student{
int id;
String name;
private Student(int id){
this.id = id;
}

private Student(int id, String name){
this.id = id;
this.name = name;
}

public static Student createInstance(int id , String name){
return new Student(id,name);
}

public static Student createInstance(int id){
return new Student(id);
}

public String toString(){
return id+": "+name;
}
}

沒有留言:

張貼留言